【问题标题】:How to return two substrings separated by whitespace from NSString in Objective-C如何在Objective-C中从NSString返回两个由空格分隔的子字符串
【发布时间】:2015-09-29 01:12:43
【问题描述】:

给定一个字符串“a b c d”,我想返回以下格式的子字符串:

"a b", "b c", "c d"

我在以最有效的方式来完成这个概念时遇到了一些麻烦。

代码格式:

NSString *sentence = @"Hello I am a string";

我希望它返回以下内容:

“你好,我”, “我是”, “我是”, “一个字符串”

【问题讨论】:

    标签: ios objective-c regex algorithm nsstring


    【解决方案1】:

    试试这个:

    NSString * sentence = @"Hello I am a string";
    NSArray * components = [sentence componentsSeparatedByString:@" "];
    NSMutableArray * substrings = [[NSMutableArray alloc] init];
    
    for (int i = 0; i < components.count - 1; i++) {
        NSString * str = [NSString stringWithFormat:@"%@ %@", components[i], components[i+1]];
        [substrings addObject:str];
    }
    
    for (NSString * str in substrings) {
        NSLog(@"%@", str);
    }
    

    【讨论】:

    • 这太棒了!我想知道是否有更快的方法。
    【解决方案2】:

    你可以试试:

               test=@"abcd";
     [NSString stringWithFormat: @"%@ %@ %@", [test substringWithRange:NSMakeRange(0,2)],[test substringWithRange:NSMakeRange(1,2)],
                           [test substringWithRange:NSMakeRange(2,2)]];
    

    【讨论】:

    • 不错。我也希望它假设我真的不知道所有空格的位置,所以如果它是一个非常长的字符串,我可以找到所有空格的位置,然后找到两个由分隔的子字符串空格。
    猜你喜欢
    • 1970-01-01
    • 2011-06-16
    • 2013-02-15
    • 2014-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多