如何使用Objective-C分隔string空间?

假设我有这样一个string:

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

我想分开这个string:

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

谢谢。

 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 != ''"]]; 

键入这个forms未经testing

我会build议一个两步的问题:

 NSArray *wordsAndEmptyStrings = [yourLongString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; NSArray *words = [wordsAndEmptyStrings filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]]; 

这对我有效

 NSString * str = @"Hi Hello How Are You ?"; NSArray * arr = [str componentsSeparatedByString:@" "]; NSLog(@"Array values are : %@",arr); 

用块做这个很容易,试试这样的:

 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]; }]; 
 NSString * mainString = @"Today is your day"; NSArray * array = [mainString componentsSeparatedByString:@" "]; NSLog(@"Expected string is : %@",array); 

我需要分割一个NSString,本质上是一个logging(行)到其各自的现场组件。 每个字段使用TAB字符分隔。

我发现这对我有用。

 NSString *string = @"Imagine this is a string with tabs in it."; NSArray *array = [string componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"\t"]]; NSLog(@"%@", array); 

显然,一个标签不是一个空间。 但是,对于想要用特定字符拆分string的人来说,上面的内容可能是有用的。

希望它可以帮助别人。