How to separate string by space using Objective-C?

主宰稳场 提交于 2019-12-03 02:34:38

问题


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.


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



回答2:


I'd suggest a two-step aproach:

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



回答3:


This has worked for me

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



回答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];
}];



回答5:


NSString * mainString = @"Today is your day";
NSArray * array = [mainString componentsSeparatedByString:@" "];
NSLog(@"Expected string is : %@",array);


来源:https://stackoverflow.com/questions/4814641/how-to-separate-string-by-space-using-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!