给定一个字符串“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/