如何 return 在 Objective-C 中从 NSString 中用空格分隔的两个子字符串
How to return two substrings separated by whitespace from NSString in Objective-C
给定一个字符串 "a b c d",我想 return 以下格式的子字符串:
"a b",
"b c",
"c d"
我在以最有效的方式及时完成这个概念时遇到了一些麻烦。
代码格式:
NSString *sentence = @"Hello I am a string";
我想要return以下内容:
"Hello I",
"I am",
"am a",
"a string"
您可以尝试类似的方法:
test=@"abcd";
[NSString stringWithFormat: @"%@ %@ %@", [test substringWithRange:NSMakeRange(0,2)],[test substringWithRange:NSMakeRange(1,2)],
[test substringWithRange:NSMakeRange(2,2)]];
试试这个:
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);
}
给定一个字符串 "a b c d",我想 return 以下格式的子字符串:
"a b", "b c", "c d"
我在以最有效的方式及时完成这个概念时遇到了一些麻烦。
代码格式:
NSString *sentence = @"Hello I am a string";
我想要return以下内容:
"Hello I", "I am", "am a", "a string"
您可以尝试类似的方法:
test=@"abcd";
[NSString stringWithFormat: @"%@ %@ %@", [test substringWithRange:NSMakeRange(0,2)],[test substringWithRange:NSMakeRange(1,2)],
[test substringWithRange:NSMakeRange(2,2)]];
试试这个:
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);
}