fs_tigre fs_tigre - 3 months ago 9
Swift Question

Delete all characters after a certain character from a string in Swift

I have a

textField
and I would like to remove all character after a certain character.

For instance if what I have in the textField is the word
Orange
and I want to remove all characters after the
n
I would like to get
Ora
after the deletion.

How can I delete all characters after a certain character from a string in Swift?

Thanks

Answer

You can use rangeOfString and substringToIndex to its startIndex as follow:

let word = "orange"
if let startIndex = word.rangeOfString("n")?.startIndex {
    print(word.substringToIndex(startIndex))  // "Ora"
}