Get the string up to a specific character

后端 未结 4 1292
再見小時候
再見小時候 2021-01-07 14:21
var hello = \"hello, how are you?\"

var hello2 = \"hello, how are you @tom?\"

i want to delete every letter behind the @ sign.

result shou

4条回答
  •  [愿得一人]
    2021-01-07 15:15

    Expanding on @appzYourLife answer, the following will also trim off the whitespace characters after removing everything after the @ symbol.

    import Foundation
    
    var str = "hello, how are you @tom"
    
    if str.contains("@") {
        let endIndex = str.range(of: "@")!.lowerBound
        str = str.substring(to: endIndex).trimmingCharacters(in: .whitespacesAndNewlines)
    }
    print(str) // Output - "hello, how are you"
    

    UPDATE:

    In response to finding the last occurance of the @ symbol in the string and removing it, here is how I would approach it:

    var str = "hello, how are you @tom @tim?"
    if str.contains("@") {
        //Reverse the string
        var reversedStr = String(str.characters.reversed())
        //Find the first (last) occurance of @
        let endIndex = reversedStr.range(of: "@")!.upperBound
        //Get the string up to and after the @ symbol
        let newStr = reversedStr.substring(from: endIndex).trimmingCharacters(in: .whitespacesAndNewlines)
    
        //Store the new string over the original
        str = String(newStr.characters.reversed())
        //str = "hello, how are you @tom"
    }
    

    Or looking at @appzYourLife answer use range(of:options:range:locale:) instead of literally reversing the characters

    var str = "hello, how are you @tom @tim?"
    if str.contains("@") {
        //Find the last occurrence of @
        let endIndex = str.range(of: "@", options: .backwards, range: nil, locale: nil)!.lowerBound
        //Get the string up to and after the @ symbol
        let newStr = str.substring(from: endIndex).trimmingCharacters(in: .whitespacesAndNewlines)
    
        //Store the new string over the original
        str = newStr
        //str = "hello, how are you @tom"
    }
    

    As an added bonus, here is how I would approach removing every @ starting with the last and working forward:

    var str = "hello, how are you @tom and @tim?"
    if str.contains("@") {
    
        while str.contains("@") {
            //Reverse the string
            var reversedStr = String(str.characters.reversed())
            //Find the first (last) occurance of @
            let endIndex = reversedStr.range(of: "@")!.upperBound
            //Get the string up to and after the @ symbol
            let newStr = reversedStr.substring(from: endIndex).trimmingCharacters(in: .whitespacesAndNewlines)
    
            //Store the new string over the original
            str = String(newStr.characters.reversed())
        }
        //after while loop, str = "hello, how are you"
    }
    

提交回复
热议问题