1

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 your number!"

I want to extract "12345" to a variable.

In Java, I'd do something like:

String myStr = "12345 is your number!";
return myStr.substring(0, myStr.indexOf(" "));

How do I do something similar in Swift? I don't want to hard-code any assumptions about what the ending index will be. It might be 5 characters in, it might not. I just want to take the substring of everything up to the first occurrence of " ", wherever that might be.

The closest I've gotten so far is:

var myMessage  = "12345 is your number!"
myMessage.endIndex.advancedBy(myMessage.characters.count - myMessage.characters.indexOf(" "))

but it doesn't compile for reasons I don't fully yet grok("Binary operator '-' cannot be applied to operands of type Distance (aka 'Int') and 'String.CharacterView.Index?'")

Any help on this is appreciated. Thank you.

3 Answers 3

6

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
1

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 ;)

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.