Get the string up to a specific character

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

    let text = "hello, how are you @tom?"
    let trimSpot = text.index(of: "@") ?? text.endIndex
    let trimmed = text[..

    Since a string is a collection of Character type, it can be accessed as such. The second line finds the index of the @ sign and assigns its value to trimSpot, but if it is not there, the endIndex of the string is assigned through the use of the nil coalescing operator

        ??
    

    The string, or collection of Characters, can be provided a range that will tell it what characters to get. The expression inside of the brackets,

        ..

    is a range from 0 to trimSpot-1. So,

        text[..

    returns an instance of type Substring, which points at the original String instance.

提交回复
热议问题