views:

10217

answers:

5

What is the best way to tokenize/split a NSString in Objective-C?

+39  A: 

Found this at http://borkware.com/quickies/one?topic=NSString (useful link):

NSString *string = @"oop:ack:bork:greeble:ponies";
NSArray *chunks = [string componentsSeparatedByString: @":"];

Hope this helps!

Adam

Adam Alexander
+9  A: 

If you just want to split a string, use -[NSString componentsSeparatedByString:]. For more complex tokenization, use the NSScanner class.

Chris Hanson
+2  A: 

Hey ggarber, if your tokenization needs are more complex, check out my open source Cocoa String tokenizing/parsing toolkit: TDParseKit:

http://code.google.com/p/todparsekit/

For simple splitting of strings using a delimiter char (like ':'), TDParseKit would definitely be overkill. But again, for complex tokenization needs, TDParseKit is extremely powerful/flexible.

Todd Ditchendorf
+5  A: 

Everyone has mentioned componentsSeparatedByString: but you can also use CFStringTokenizer (remember that an NSString and CFString are interchangeable) which will tokenize natural languages too (like Chinese/Japanese which don't split words on spaces).

Matt Gallagher
And, in Mac OS X 10.6 and later, NSString has methods `enumerateLinesUsingBlock:` and `enumerateSubstringsInRange:options:usingBlock:`, the latter of which is a block-based version of CFStringTokenizer. http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/enumerateLinesUsingBlock: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/enumerateSubstringsInRange:options:usingBlock:
Peter Hosey
A: 

I then use objectAtIndex to get the "3rd word" in the sentence: @"oop:ack:bork:greeble:ponies"

Or is there a quicker way to do this all at once?

Bonnie
You should ask that as a separate question, not in an answer on this question, since it doesn't answer this question.
Peter Hosey
Not sure why anyone would want help to split up a string... but then do absolutely nothing with the individual words.
Bonnie