How do I get the string before a certain character in swift? The code below is how I did it in Objective C, but can't seem to perform the same task in Swift. Any tips or suggestions on how to achieve this? rangeOfString
seems to not work at all in swift (although Swift has been acting up for me again).
NSRange range = [time rangeOfString:@" "]; NSString *startDate = [time substringToIndex:range.location];
As you can see from the code above I am able to get the string before the space character in Objective C.
Edit : If I try something like this
var string = "hello Swift" var range : NSRange = string.rangeOfString("Swift")
I get the following error.
Cannot convert the expression's type 'NSString' to type '(String, options: NSStringCompareOptions, range: Range?, locale: NSLocale?)'
Not sure what I did wrong exactly or how to resolve it correctly.
You can use components(separatedBy:) method to divide a string into substrings by specifying string separator. let str = "Hello! Swift String."
In Swift, the first property is used to return the first character of a string.
Swift 2 String Search The contains() function has been replaced by the contains() method that can be invoked on the characters property of the new Swift 2 String. The find() function has been replaced with a new method called indexOf() that works on your characters property.
Use componentsSeparatedByString() as shown below:
var delimiter = " " var newstr = "token0 token1 token2 token3" var token = newstr.components(separatedBy: delimiter) print (token[0])
Or to use your specific case:
var delimiter = " token1" var newstr = "token0 token1 token2 token3" var token = newstr.components(separatedBy: delimiter) print (token[0])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With