Get the string up to a specific character

后端 未结 4 1270
再見小時候
再見小時候 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 14:54

    Try regular expressions, they are much safer (if you know what you are doing...)

      let hello2 = "hello, how are you @tom, @my @next @victim?"
    
        let deletedStringsAfterAtSign = hello2.replacingOccurrences(of: "@\\w+", with: "", options: .regularExpression, range: nil)
    
        print(deletedStringsAfterAtSign)
        //prints "hello, how are you ,   ?"
    

    And this code removes exactly what you need and leaves the characters after the strings clear, so you can see the , and ? still being there. :)

    EDIT: what you asked in comments to this answer:

      let hello2 = "hello, how are you @tom, @my @next @victim?"
    
      if let elementIwannaAfterEveryAtSign = hello2.components(separatedBy: " @").last
      {
        let deletedStringsAfterAtSign = hello2.replacingOccurrences(of: "@\\w+", with: elementIwannaAfterEveryAtSign, options: .regularExpression, range: nil)
        print(deletedStringsAfterAtSign)
        //prints hello, how are you victim?, victim? victim? victim??
        }
    

提交回复
热议问题