How do I take a substring to the first index of a character?

后端 未结 3 1303
予麋鹿
予麋鹿 2021-01-24 12:42

I\'m very new to Swift; I\'ve spent the morning reading StackOverflow and trying many strategies, in vain, to accomplish the following:

I have a string, say \"12345 is

3条回答
  •  温柔的废话
    2021-01-24 13:06

    Something like this should work:

    myMessage.substringToIndex(myMessage.characters.indexOf(" ")!)
    

    Note that in this code I force unwrapped the optional. If you're not guaranteed to have that space in the string, it might make more sense to have the index in a optional binding.

    With optional binding, it would look something like this:

    if let index = myMessage.characters.indexOf(" ") {
        let result = myMessage.substringToIndex(index)
    }
    

提交回复
热议问题