swift: how can I delete a specific character?

If you need to remove characters only on both ends, you can use stringByTrimmingCharactersInSet(_:)

let delCharSet = NSCharacterSet(charactersInString: "! ")

let s1 = "! aString! !"
let s1Del = s1.stringByTrimmingCharactersInSet(delCharSet)
print(s1Del) //->aString

let s2 = "! anotherString !! aString! !"
let s2Del = s2.stringByTrimmingCharactersInSet(delCharSet)
print(s2Del) //->anotherString !! aString

If you need to remove characters also in the middle, "reconstruct from the filtered output" would be a little bit more efficient than repeating single character removal.

var tempUSView = String.UnicodeScalarView()
tempUSView.appendContentsOf(s2.unicodeScalars.lazy.filter{!delCharSet.longCharacterIsMember($0.value)})
let s2DelAll = String(tempUSView)
print(s2DelAll) //->anotherStringaString

If you don't mind generating many intermediate Strings and Arrays, this single liner can generate the expected output:

let s2DelAll2 = s2.componentsSeparatedByCharactersInSet(delCharSet).joinWithSeparator("")
print(s2DelAll2) //->anotherStringaString

I find that the filter method is a good way to go for this sort of thing:

let unfiltered = "!   !! yuahl! !"

// Array of Characters to remove
let removal: [Character] = ["!"," "]

// turn the string into an Array
let unfilteredCharacters = unfiltered.characters

// return an Array without the removal Characters
let filteredCharacters = unfilteredCharacters.filter { !removal.contains($0) }

// build a String with the filtered Array
let filtered = String(filteredCharacters)

print(filtered) // => "yeah"

// combined to a single line
print(String(unfiltered.characters.filter { !removal.contains($0) })) // => "yuahl"

Swift 3

In Swift 3, the syntax is a bit nicer. As a result of the Great Swiftification of the old APIs, the factory method is now called trimmingCharacters(in:). Also, you can construct the CharacterSet as a Set of single-character Strings:

let string = "!   !! yuahl! !"
string.trimmingCharacters(in: [" ", "!"]) // "yuahl" 

If you have characters in the middle of the string you would like to remove as well, you can use components(separatedBy:).joined():

let string = "!   !! yu !ahl! !"
string.components(separatedBy: ["!", " "]).joined() // "yuahl" 

H/T @OOPer for the Swift 2 version


Swift 5+

let myString = "aaaaaaaabbbb"
let replaced = myString.replacingOccurrences(of: "bbbb", with: "") // "aaaaaaaa"