Robert D
Robert D

Reputation: 125

Replacing multiple strings with Objective-C

I am currently doing an experiment where I input text into a UITextField, and the text is searched to see if it has certain strings in it. If it finds the certain text, it should replace it, and send it to a UITextView. (Think of a super-simplified translator)

The problem I am having with it is that it only sends the text I last paired. For exammple,

NSString *mainString = [[NSString alloc] initWithString:field.text];
NSArray *stringsToReplace = [[NSArray alloc] initWithObjects:@"The",@"dog",@"cried", nil];
NSArray *stringsReplaceBy = [[NSArray alloc] initWithObjects:@"ehT",@"god",@"deirc", nil];
for (int i=0; i< [stringsReplaceBy count]; i++)
{
    look.text = [mainString stringByReplacingOccurrencesOfString:[stringsToReplace objectAtIndex:i] withString:[stringsReplaceBy objectAtIndex:i]];
}

When I type in, "The dog cried." it should be saying "ehT god deirc." However, it is responding with "The dog deirc."

Please help.

Upvotes: 0

Views: 97

Answers (1)

Sebastian
Sebastian

Reputation: 7720

You are calling stringByReplaceingOccurencesOfString three times on the same string:

for (int i=0; i< [stringsReplaceBy count]; i++)
{
    look.text = [mainString stringByReplacingOccurrencesOfString:[stringsToReplace objectAtIndex:i] withString:[stringsReplaceBy objectAtIndex:i]];
}

Instead, save the result into another string object:

NSString *modifiedString = mainString;
for (int i=0; i< [stringsReplaceBy count]; i++)
{
    modifiedString = [modifiedString stringByReplacingOccurrencesOfString:[stringsToReplace objectAtIndex:i] withString:[stringsReplaceBy objectAtIndex:i]];
}
look.text = modifiedString;

Upvotes: 1

Related Questions