例如
NSString *string = @"I need help finding a string";
NSString *newString = @"need";
我需要这个不仅适用于此字符串。一个例子是取一个字符串并删除单词“I”之后和单词“help”之前的所有内容。 非常感谢你!
从评论中删除易读性:
NSString *string = @"I need help finding a string";
NSRange rr2 = [TWEET rangeOfString:@"I "];
NSRange rr3 = [TWEET rangeOfString:@" help"];
int lengt = rr3.location - rr2.location;
int location = rr2.location + rr2.length;
NSRange aa;
aa.location = location;
aa.length = lengt;
NSString *link;
link = [TWEET substringWithRange:aa];
NSLog(@"The link is %@", link);
答案 0 :(得分:0)
一种方法是将字符串拆分成单个单词,然后迭代它,首先搜索第一个单词,同时将每个单词添加到新字符串,直到找到它并搜索第二个单词并在找到之后只是添加剩余的单词。
在代码中看起来像这样:
NSString *myString = @"I need help finding a string";
NSString *firstWord = @"need";
NSString *secondWord = @"a";
NSMutableString *newString = [NSMutableString stringWithString:@""];
int index = 0;
for (NSString *word in [myString componentsSeparatedByString:@" "]) {
if(index == 0) {
if([word isEqualToString:firstWord])
index = 1;
[newString appendFormat:@"%@ ", word];
}
else if(index == 1) {
if([word isEqualToString:secondWord])
index = 2;
}
else
[newString appendFormat:@"%@ ", word];
}