在nsstring中查找并替换所有内容 [英] Find and Replace all within nsstring

查看:92
本文介绍了在nsstring中查找并替换所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找单词列表,如果匹配我正在替换。如果匹配单词出现超过一次,则打击代码可以正常工作。

I am trying to find list of words , if matches i am replacing. the blow code works but it is not replacing if the matching word occurs more than one time.

我认为我需要使用while而不是if循环,但是我我无法让它发挥作用。

And i think i need to use while instead of if loop here , but i am not able to make it to work.

我很挣扎请让我知道

    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为你做到了......

You don't have to reinvent the wheel; Cocoa does that for you...

代码:

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);

提示:
我们将替换每一个一个出现aList [0]与bList [0],aList [1]与bList [1],依此类推......; - )

HINT : We'll be replacing each and every one occurence of aList[0] with bList[0], aList[1] with bList[1], and so on... ;-)

这篇关于在nsstring中查找并替换所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆