假设我有一个像这样的字符串:
hello world this may have lots of sp:ace or little space
我想把这个字符串分开:
@"hello", @"world", @"this", @"may", @"have", @"lots", @"of", @"sp:ace", @"or", @"little", @"space"
谢谢。
答案 0 :(得分: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 != ''"]];
答案 1 :(得分:21)
我建议采用两步法:
NSArray *wordsAndEmptyStrings = [yourLongString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *words = [wordsAndEmptyStrings filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]];
答案 2 :(得分:21)
这对我有用
NSString * str = @"Hi Hello How Are You ?";
NSArray * arr = [str componentsSeparatedByString:@" "];
NSLog(@"Array values are : %@",arr);
答案 3 :(得分:5)
用块做这个很容易,尝试这样的事情:
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];
}];
答案 4 :(得分:5)
NSString * mainString = @"Today is your day";
NSArray * array = [mainString componentsSeparatedByString:@" "];
NSLog(@"Expected string is : %@",array);