ios - 如何从 Objective-C 中的 NSString 返回两个由空格分隔的子字符串

标签 ios objective-c regex algorithm nsstring

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

"一个 b", “BC”, “cd”

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

代码格式:

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

我希望它返回以下内容:

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

最佳答案

试试这个:

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

关于ios - 如何从 Objective-C 中的 NSString 返回两个由空格分隔的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32834127/

相关文章:

ios - XIB 中的 UITabelViewCell 将被实例化更多次

ios - 延迟背景颜色和标签更新但 NSLog 工作正常

ios - Objective-C GCD : Do multiple dispatch threads make things faster?

iphone - 删除核心数据中子实体的规则

ios - UIApplicationDelegate 与 NSApplicationDelegate,MainMenu.xib

java - Android 正则表达式不匹配

regex - 下面的两个 sed 命令有什么区别?

ios - swift:合并不重叠的图像

objective-c - NSTextView 未将文本绘制到 NSImage 上

python - 子字符串之间的对齐错误