How to separate string by space using Objective-C?
38,239
Solution 1
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 != ''"]];
Solution 2
I'd suggest a two-step aproach:
NSArray *wordsAndEmptyStrings = [yourLongString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *words = [wordsAndEmptyStrings filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]];
Solution 3
This has worked for me
NSString * str = @"Hi Hello How Are You ?";
NSArray * arr = [str componentsSeparatedByString:@" "];
NSLog(@"Array values are : %@",arr);
Solution 4
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];
}];
Related videos on Youtube
Author by
user448236
Updated on May 25, 2020Comments
-
user448236 almost 4 years
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.
-
EmptyStack over 13 yearsYour recipe is here stackoverflow.com/questions/758212/…
-
vikingosegundo over 13 yearsI 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.
-
-
deniz about 3 yearsWhat if the characters in the input string are separated by more than one space (as is the case in this question)?