49

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.

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
user448236
  • 683
  • 2
  • 7
  • 13
  • Your recipe is here http://stackoverflow.com/questions/758212/objective-c-strip-out-whitespace-from-nsstring/1427224#1427224 – EmptyStack Jan 27 '11 at 09:39
  • 3
    I can't see, why this question is voted as "not a real question". The OP says what is given and what is needed to achieve. – vikingosegundo Jan 27 '11 at 10:00

4 Answers4

81
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 != ''"]];
Zoe
  • 27,060
  • 21
  • 118
  • 148
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
23

I'd suggest a two-step aproach:

NSArray *wordsAndEmptyStrings = [yourLongString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *words = [wordsAndEmptyStrings filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]];
danyowdee
  • 4,658
  • 2
  • 20
  • 35
22

This has worked for me

NSString * str = @"Hi Hello How Are You ?";
NSArray * arr = [str componentsSeparatedByString:@" "];
NSLog(@"Array values are : %@",arr);
Mohit
  • 3,708
  • 2
  • 27
  • 30
5

It's very easy to do this with blocks, try something like this :

NSString* s = @"hello world       this may     have lots   of space or little      space";
NSMutableArray* ar = [NSMutableArray array];
[s enumerateSubstringsInRange:NSMakeRange(0, [s length]) options:NSStringEnumerationByWords usingBlock:^(NSString* word, NSRange wordRange, NSRange enclosingRange, BOOL* stop){
    [ar addObject:word];
}];
Nyx0uf
  • 4,609
  • 1
  • 25
  • 26