user198725878
user198725878

Reputation: 6386

Find and Replace all within 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.

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


    }

Upvotes: 1

Views: 9487

Answers (3)

Dr.Kameleon
Dr.Kameleon

Reputation: 22820

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

Upvotes: 15

iOS_Developer
iOS_Developer

Reputation: 183

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.

Upvotes: 2

wbyoung
wbyoung

Reputation: 22493

Look at NSString's stringByReplacingOccurrencesOfString:withString: method.

Upvotes: 3

Related Questions