s6luwJ0A3I s6luwJ0A3I - 3 years ago 58
iOS Question

How to replace occurrences of multiple strings with multiple other strings [NSString]

NSString *string = [myString stringByReplacingOccurrencesOfString:@"<wow>" withString:someString];

I have this code. Now suppose my app's user enters two different strings I want to replace with two different other strings, how do I achieve that? I don't care if it uses private APIs, i'm developing for the jailbroken platform. My user is going to either enter or or . I want to replace any occurrences of those strings with their respective to-be-replaced-with strings :)

Thanks in advance :P

Answer Source

Both dasblinkenlight’s and Matthias’s answers will work, but they both result in the creation of a couple of intermediate NSStrings; that’s not really a problem if you’re not doing this operation often, but a better approach would look like this.

NSMutableString *myStringMut = [[myString mutableCopy] autorelease];
[myStringMut replaceOccurrencesOfString:@"a" withString:somethingElse];
[myStringMut replaceOccurrencesOfString:@"b" withString:somethingElseElse];
// etc.

You can then use myStringMut as you would’ve used myString, since NSMutableString is an NSString subclass.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download