Remove all characters after a specific character from a string in Swift

I have a textField and I would like to delete all characters after a specific character.

For example, if I have the word Orange in textField and I want to delete all characters after n , I would like to get Ora after deleting.

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

thanks

+11
string uitextfield swift nsstring
source share
2 answers

You can use rangeOfString and substringToIndex for its startIndex as follows:

Swift 2

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

Swift 3

 let word = "orange" if let index = word.range(of: "n")?.lowerBound { print(word.substring(to: index)) // "ora" } 

Swift 4

 let word = "orange" if let index = word.range(of: "n")?.lowerBound { let substring = word[..<index] // "ora" // or let substring = word.prefix(upTo: index) // "ora" // (see picture below) Using the prefix(upTo:) method is equivalent to using a partial half-open range as the collections subscript. // The subscript notation is preferred over prefix(upTo:). let string = String(substring) print(string) // "ora" } 

enter image description here

+21
source share

You can do it as follows:

 guard let range = text.rangeOfString("Your String or Character here") else { return the text } return text.substringToIndex(range.endIndex) // depending on if you want to delete before a certain string, you would use range.startIndex 
+1
source share

All Articles