How to separate string by space using Objective-C?

前端 未结 5 2137
清歌不尽
清歌不尽 2021-01-30 16:16

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

相关标签:
5条回答
  • 2021-01-30 16:52

    This has worked for me

    NSString * str = @"Hi Hello How Are You ?";
    NSArray * arr = [str componentsSeparatedByString:@" "];
    NSLog(@"Array values are : %@",arr);
    
    0 讨论(0)
  • 2021-01-30 16:55
    NSString * mainString = @"Today is your day";
    NSArray * array = [mainString componentsSeparatedByString:@" "];
    NSLog(@"Expected string is : %@",array);
    
    0 讨论(0)
  • 2021-01-30 16:59

    I'd suggest a two-step aproach:

    NSArray *wordsAndEmptyStrings = [yourLongString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSArray *words = [wordsAndEmptyStrings filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]];
    
    0 讨论(0)
  • 2021-01-30 17:02
    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 != ''"]];
    
    0 讨论(0)
  • 2021-01-30 17:09

    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];
    }];
    
    0 讨论(0)
提交回复
热议问题