1

Hi How can i replace NSString use array to another array like this

@"Hello world"

{a,b,c,d,e,...} -> {1,2,3,4,5,..} = @"H5llo worl4"

and can i replace without array?? totally i want to replace 10 characters of an String to another 10 characters. How can i do that?

2 Answers 2

1

Loop through the array and replace each character in turn :

// Get the two arrays of characters to replace and their replacements
NSArray *fromArray = [NSArray arrayWithObjects:@"a", @"b", @"c", @"d", @"e", nil];
NSArray *toArray = [NSArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", nil];

// Make a mutable version of our string
NSMutableString *newString = [NSMutableString stringWithString:@"Hello World"];

// Deal with each replacement in turn
for (uint n = 0; n < [fromArray count]; ++n)
    [newString replaceOccurrencesOfString:[fromArray objectAtIndex:n] withString:[toArray objectAtIndex:n] options:NSLiteralSearch range:NSMakeRange(0, [newString length])];

// Output the new string
NSLog(@"%@", newString);

This code's not great though - what if the two arrays are different lengths?

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks no they have same length.
@mamrezo you'd better have a look at efficiency here and maybe correctness if you can have overlapping substitutions
0

You could use an NSDictionary to store your associative array (which contains the replacement string and its key).

Then you can loop through your elements in the NSDictionary using a fast enumeration so that you can could substitute it by using stringByReplacingOccurrencesOfString:withString:options:range:.

This method is better than simply calling replaceOccurrencesOfString:withString: because by specifying the range you can avoid from re-looping on an already subsituted substring and also you will avoid the application of chained substitutions (ie. a->i, i->4)

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.