Swift Program to Find the Duplicate Characters in a String


In Swift, a string is a collection of characters so it can contain duplicate as well as unique characters. So to find the duplicate characters in a string we create a dictionary/array to store the count of each character and then add those characters in the array whose count is greater than 1.

Example

Input: “sky is pink”
Output: Duplicate char: [“s”, “i”, “k”]

Here, the input string contains three duplicate characters that are “s”, “i”, and “k”.

To find the duplicate characters in a string we are going to use the following methods −

  • User-defined function

  • Using Array() and filter() methods

  • Using NSCountedSet

Method 1: Using a user-defined function

To find the duplicate characters in a string we are going to create a function which takes the input string as a parameter and returns all the duplicate elements present in the input string.

Algorithm

  • Step 1 − Create a function to find the duplicate characters in a string.

  • Step 2 − Inside the function convert the input string into lowercase so that we can perform the operation very efficiently.

  • Step 3 − Create a dictionary to store the character and their count.

  • Step 4 − Create an array to store duplicate characters.

  • Step 5 − Iterate through each character of the given string.

  • Step 6 − If a character is already present in the dictionary, then increase the counter by 1. Otherwise, add the character to the dictionary with count 1.

  • Step 7 − After calculating the occurrences of the character we iterate through each pair and add those characters in the array whose counter is greater than 1.

  • Step 8 − After completing the loop return the array.

  • Step 9 − Create a string

  • Step 10 − Call the function and pass the input string in it and store the result in an array.

  • Step 11 − Display the output.

Example

In the following Swift program, we will find duplicate characters in a string. So for that, we create a function which takes a string as an input. This function creates a dictionary to store the character along with their count. Then it uses a for-in loop to iterate through each character of the string and increase the counter by 1 if duplicate characters are found, otherwise, it adds a character with count 1 in the dictionary. After counting all occurrences of the characters the function iterates through the key-value pairs of the dictionary using a for-in loop and adds only those characters in the array whose count is greater than 1. After iterating through all the key-value pairs this function returns an array containing duplicate elements.

import Foundation
import Glibc

func findDuplicateChar(myStr: String) -> [Character] 
{
    let newStr = myStr.lowercased()
    var charCount = [Character: Int]()
    var duplicateChar = [Character]()

    for c in newStr 
    {
        if let counter = charCount[c] 
        {
            charCount[c] = counter + 1
        } else {
            charCount[c] = 1
        }
    }

    for (c, counter) in charCount 
    {
        if counter > 1 
        {
            duplicateChar.append(c)
        }
    }
    return duplicateChar
}

let input = "Tom travel to Japan"
let duplicateChar = findDuplicateChar(myStr: input)
print("Duplicate Characters are:", duplicateChar)

Output

Duplicate Characters are: ["t", "o", "a", " "]

Method 2: Using Array() and filter() methods

To find the duplicate characters in a string first convert the input string into an array of characters using Array() initializer.

Syntax

Array(inputString)

Here the Array() initialiser takes only one parameter and converts it into the array.

After that, we will use the filter() method to find the duplicate characters. The filter() method returns an array of those elements that satisfy the given criteria.

Syntax

func filter(mSlosure)

Here mClosure is the closure which takes elements one by one and checks if it matches the given criteria or not. If yes, then include that element in the resultant array.

Algorithm

  • Step 1 − Create a string.

  • Step 2 − Convert the input string into an array of characters.

  • Step 3 − Find duplicate characters.

  • Step 4 − Display the output.

Example

In the following Swift program, we will find duplicate characters in a string. So for that, create a string. Then using Array() initializer to convert the string into an array of characters. Then use the filter() function to count the occurrence of each character in the given array. If the count is greater than 1, then the character is a duplicate, so add that element to the new array. Otherwise, not. After filtering all the characters we will check if the new array is empty or not. If the new array is empty, then print “no duplicate characters found”. Otherwise, print duplicate characters.

import Foundation
import Glibc

var StringVal = "Meeta is cooking Paratha"
let charArray = Array(StringVal)
let duplicatesChars = charArray.filter({ c in
   return charArray.filter({ $0 == c }).count > 1
})

if duplicatesChars.isEmpty {
   print("No duplicate characters is found.")
} else {
   print("Duplicate characters: \(duplicatesChars)")
}

Output

Duplicate characters: ["e", "e", "t", "a", " ", "i", " ", "o", "o", "i", " ", "a", "a", "t", "a"]

Method 3: Using NSCountedSet

To find the duplicate characters in a string we can also use NSCountedSet class. It is an unordered mutable collection of distinct objects.

Syntax

NSCountedSet()

This constructor is used to create a counted set object.

Algorithm

  • Step 1 − Create a string.

  • Step 2 − Convert the input string into an array of characters.

  • Step 3 − Find duplicate characters.

  • Step 4 − Display the output.

Example

In the following Swift program, we will find duplicate characters in a string. So for that, create a string. Then using Array() initializer to convert the string into an array of characters. Then use the filter() function to count the occurrence of each character in the given array. If the count is greater than 1, then the character is a duplicate, so add that element to the new array. Otherwise, not. After filtering all the characters we will check if the new array is empty or not. If the new array is empty, then print “no duplicate characters found”. Otherwise, print duplicate characters.

import Foundation
import Glibc

var StringVal = "Meeta is cooking Paratha"
let charArray = Array(StringVal)
let duplicatesChars = charArray.filter({ c in
   return charArray.filter({ $0 == c }).count > 1
})

if duplicatesChars.isEmpty {
   print("No duplicate characters is found.")
} else {
   print("Duplicate characters: \(duplicatesChars)")
}

Output

Duplicate characters: ["e", "e", "t", "a", " ", "i", " ", "o", "o", "i", " ", "a", "a", "t", "a"]

Method 3: Using NSCountedSet

To find the duplicate characters in a string we can also use NSCountedSet class. It is an unordered mutable collection of distinct objects.

Syntax

NSCountedSet()

This constructor is used to create a counted set object.

Algorithm

  • Step 1 − Create a string.

  • Step 2 − Convert the input string into an array of characters.

  • Step 3 − Find duplicate characters.

  • Step 4 − Display the output.

Example

In the following Swift program, we will find duplicate characters in a string. So for that, create a string. Then create an object of NSCountedSet class using NSCounted() constructor to keep track of the counted characters. Then we will use Array() initializer to convert the string into an array of characters. Then add elements in countedSet using add() method. Then create a new array of character types to store the result. Now iterate through each character and check if the count of the character is greater than 1. If yes, then add that character to the new array. Otherwise, not. After checking all the characters we will check if the new array is empty or not. If the new array is empty, then print “no duplicate characters found”. Otherwise, print duplicate characters.

import Foundation
import Glibc

var StringVal = "Meeta is cooking Paratha"

let countedSet = NSCountedSet()
let charArray = Array(StringVal)
charArray.forEach { countedSet.add($0) }

var duplicateChar = [Character]()

// Iterate through each character and find duplicates
for c in charArray {
  if countedSet.count(for: c) > 1 && !duplicateChar.contains(c) {
    duplicateChar.append(c)
  }
}

if duplicateChar.isEmpty {
   print("No duplicate characters found.")
} else {
   print("Duplicate characters: \(duplicateChar)")
}

Output

Duplicate characters: ["e", "t", "a", " ", "i", "o"]

Conclusion

So this is how we can find the duplicate characters in a string. Finding duplicate characters helps to identify errors or inconsistencies, data validation, string analysis, string manipulation, etc. So using the above methods you can efficiently find all the duplicate characters present in the string.

Updated on: 13-Jun-2023

900 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements