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

后端 未结 3 1301
予麋鹿
予麋鹿 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 12:51

    With Swift 5 you can use:

    myStr.prefix(upTo: myStr.firstIndex(of: " ") ?? myStr.startIndex)
    

    You may need to cast it back to String (String(myStr.prefix(upTo: myStr.firstIndex(of: " ") ?? myStr.startIndex))) since it returns a Substring

    0 讨论(0)
  • 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)
    }
    
    0 讨论(0)
  • 2021-01-24 13:13

    You can use a regex, try this code:

    var myMessage  = "12345 is your number!"
    
    if let match = myMessage.rangeOfString("-?\\d+", options: .RegularExpressionSearch) {
    
        print(myMessage.substringWithRange(match)) // 12345
        let myNumber = Int(myMessage.substringWithRange(match)) // Then you can initialize a new variable
    }
    

    The advantage is that this method extracts only the numbers wherever they are in the String

    Hope this help ;)

    0 讨论(0)
提交回复
热议问题