Swift String – Remove Specific Characters

To remove specific set of characters from a String in Swift, take these characters to be removed in a set, and call the removeAll(where:) method on this string str, with the predicate that if the specific characters contain this character in the String.

Example

In the following program, we will take a string and remove all the vowels from it.

main.swift

</>
Copy
var str = "An apple a day, keeps doctor away!"
let removeCharacters: Set<Character> = ["p", "y"]
str.removeAll(where: { removeCharacters.contains($0) } )
print(str)

Output

Swift String - Remove Specific Characters

Conclusion

In this Swift Tutorial, we learned how to remove specific characters from a String in Swift.