我正在尝试查找单词列表,如果匹配我正在替换。打击代码有效,但如果匹配词出现多次,则不会替换。
而且我认为我需要在这里使用 while 而不是 if 循环,但我无法使其工作。
我很挣扎请告诉我
NSString *mymessage = @"for you for your information at you your at fate";
NSMutableArray *full_text_list = [[NSMutableArray alloc]init];
[full_text_list addObject:@"for"];
[full_text_list addObject:@"for your information"];
[full_text_list addObject:@"you"];
[full_text_list addObject:@"at"];
NSMutableArray *short_text_list = [[NSMutableArray alloc]init];
[short_text_list addObject:@"4"];
[short_text_list addObject:@"fyi"];
[short_text_list addObject:@"u"];
[short_text_list addObject:@"@"];
for(int i=0;i<[full_text_list count];i++)
{
NSRange range = [mymessage rangeOfString:[full_text_list objectAtIndex:i]];
if(range.location != NSNotFound) {
NSLog(@"%@ found", [full_text_list objectAtIndex:i]);
mymessage = [mymessage stringByReplacingCharactersInRange:range withString:[short_text_list objectAtIndex:i]];
}
}
最佳答案
您不必重新发明轮子; cocoa 为您做到了...
代码:
NSString* message = @"for you for your information at you your at fate";
NSMutableArray* aList = [[NSMutableArray alloc] initWithObjects:@"for your information",@"for",@"you ",@"at ",nil];
NSMutableArray* bList = [[NSMutableArray alloc] initWithObjects:@"fyi",@"4",@"u ",@"@ ",nil];
for (int i=0; i<[aList count];i++)
{
message = [message stringByReplacingOccurrencesOfString:[aList objectAtIndex:i]
withString:[bList objectAtIndex:i]];
}
NSLog(@"%@",message);
提示:
我们将用 bList[0] 替换每一次出现的 aList[0],用 bList[1] 替换 aList[1],依此类推... ;-)
关于objective-c - 在 nsstring 中查找和替换所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9786431/