0

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.

1
  • If my answer solved your problem, you should accept it. You might want to read through the help section and the about page for more info on how stack overflow works. Commented Nov 5, 2013 at 0:01

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.