问题
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
回答1:
You can use rangeOfString and substringToIndex to its startIndex as follow:
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 collection’s subscript.
// The subscript notation is preferred over prefix(upTo:).
let string = String(substring)
print(string) // "ora"
}
回答2:
You could do it like this:
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
来源:https://stackoverflow.com/questions/39184984/delete-all-characters-after-a-certain-character-from-a-string-in-swift