How to separate string by space using Objective-C?

user448236 picture user448236 · Jan 27, 2011 · Viewed 37.6k times · Source

Assume that I have a String like this:

hello world       this may     have lots   of sp:ace or little      space

I would like to seperate this String to this:

@"hello", @"world", @"this", @"may", @"have", @"lots", @"of", @"sp:ace", @"or", @"little", @"space"

Thank you.

Answer

vikingosegundo picture vikingosegundo · Jan 27, 2011
NSString *aString = @"hello world       this may     have lots   of sp:ace or little      space";
NSArray *array = [aString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
array = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF != ''"]];