objective-c - 在 nsstring 中查找和替换所有内容

标签 objective-c ios ios4 nsstring

我正在尝试查找单词列表,如果匹配我正在替换。打击代码有效,但如果匹配词出现多次,则不会替换。

而且我认为我需要在这里使用 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/

相关文章:

ios - for循环不会执行

objective-c - 如何在 Objective-C 中更改鼠标光标

ios - GLDrawElements 崩溃程序

iphone - 仅适用于 iPhone 的应用程序

objective-c - Objective-C:完成间隔计时器

ios - 如何在 Objective c 的 UITableview 中获取 NSMutableArray 的实际值而不是索引

ios - 将参数传递给实现协议(protocol)并快速扩展类的方法

iphone - 是否可以访问 iPhone 中的联系人信息屏幕?

ios - UILabel动态高度问题

iphone - switch.hidden = YES 不工作, socket 设置正确