【问题标题】:How to separate string by space using Objective-C?如何使用Objective-C按空格分隔字符串?
【发布时间】:2011-06-16 10:11:17
【问题描述】:

假设我有一个这样的字符串:

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

我想将此字符串分隔为:

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

谢谢。

【问题讨论】:

  • 我看不出,为什么这个问题被选为“不是一个真正的问题”。 OP 说明了给定的内容和需要实现的内容。

标签: objective-c nsstring nsarray whitespace


【解决方案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】:

    这对我有用

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

    【讨论】:

    • 如果输入字符串中的字符被多个空格隔开(如本题所示)怎么办?
    【解决方案3】:

    我建议分两步走:

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

    【讨论】:

      【解决方案4】:

      用积木很容易做到这一点,试试这样的:

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

      【讨论】:

        猜你喜欢
        • 2021-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多