Find and Replace all within nsstring

江枫思渺然 提交于 2019-12-11 11:08:38

问题


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.

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

I am struggling Please let me know

    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]];
        }


    }

回答1:


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

Code :

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

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




回答2:


Look at NSString's stringByReplacingOccurrencesOfString:withString: method.




回答3:


Your string (myMessage) contains "for" word 3 times. When the for loop is executing first times it is replacing the "for" with "4", After first execution of for loop your string become like "4 you 4 your in4mation at you your at fate". Because "for your information" has become "4 your in4mation". It has replaced the third "for" also.

Same way it is replacing "at" also from "in4mation" word and becoming like "in4m@ion", And finally you are getting a new string like "4 u 4 ur in4m@ion @ u ur @ f@e".

My English is not so good, I hope you got my point.



来源:https://stackoverflow.com/questions/9786431/find-and-replace-all-within-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!