Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...