Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift : How to get the string before a certain character?

Tags:

ios

swift

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.

like image 233
Danger Veger Avatar asked Apr 02 '15 20:04

Danger Veger


People also ask

How do you split a string after a specific character in Swift?

You can use components(separatedBy:) method to divide a string into substrings by specifying string separator. let str = "Hello! Swift String."

How do I get the first character of a string in Swift?

In Swift, the first property is used to return the first character of a string.

How do I find a character in a string Swift?

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.


1 Answers

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]) 
like image 89
Syed Tariq Avatar answered Sep 23 '22 06:09

Syed Tariq