我有textField
,我想删除某个角色后的所有角色。
例如,如果我在textField中的内容是单词Orange
,并且我想删除n
之后的所有字符,我希望在删除后获取Ora
。
如何删除Swift中字符串中某个字符后的所有字符?
由于
答案 0 :(得分:26)
您可以将rangeOfString和substringToIndex用于其startIndex,如下所示:
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"
}
答案 1 :(得分:1)
你可以这样做:
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