Brad Yuan Brad Yuan - 1 year ago 163
Swift Question

swift: how can I delete a specific character?

a string such as

! !! yuahl! !
, I want delete
, when I code like this

for index in InputName.characters.indices {
if String(InputName[index]) == "" || InputName.substringToIndex(index) == "!" {

have an error " fatal error: subscript: subRange extends past String end ", how should I do? THX :D

Answer Source

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()
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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download