Delete all characters after a certain character from a string in Swift [duplicate]

天涯浪子 提交于 2019-12-21 03:34:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!