48

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
  • 51,574
  • 14
  • 135
  • 174
user448236
  • 673
  • 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

80
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 stands with Ukraine
  • 25,310
  • 18
  • 114
  • 149
vikingosegundo
  • 51,574
  • 14
  • 135
  • 174
23

I'd suggest a two-step aproach:

NSArray *wordsAndEmptyStrings = [yourLongString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *words = [wordsAndEmptyStrings filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]];
danyowdee
  • 4,618
  • 2
  • 17
  • 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,628
  • 2
  • 26
  • 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,589
  • 1
  • 24
  • 26