Get the string up to a specific character

后端 未结 4 1297
再見小時候
再見小時候 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:19

    You need to find the range of the "@" and then use it to create a substring up to the index before.

    import Foundation
    
    let text = "hello, how are you @tom?"
    
    if let range = text.range(of: "@") {
        let result = text.substring(to: range.lowerBound)
        print(result) // "hello, how are you "
    }
    

    Considerations

    Please note that, following the logic you described and using the input text you provided, the output string will have a blank space as last character

    Also note that if multiple @ are presente in the input text, then the first occurrence will be used.


    Last index [Update]

    I am adding this new section to answer the question you posted in the comments.

    If you have a text like this

    let text = "hello @tom @mark @mathias"
    

    and you want the index of the last occurrency of "@" you can write

    if let index = text.range(of: "@", options: .backwards)?.lowerBound {
        print(index)    
    }
    

提交回复
热议问题