从Swift中的字符串中删除某个字符后面的所有字符

时间:2016-08-27 19:33:18

标签: swift string nsstring uitextfield

我有textField,我想删除某个角色后的所有角色。

例如,如果我在textField中的内容是单词Orange,并且我想删除n之后的所有字符,我希望在删除后获取Ora

如何删除Swift中字符串中某个字符后的所有字符?

由于

2 个答案:

答案 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"
}

Deserialize a Dictionary

答案 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