SundayMonday
SundayMonday

Reputation: 19737

Replacing list of strings in a string (Objective-c 2.0)

For example I'd like to replace all occurrences of @"a" and @"b" in @"abcdabcd" with @"z". I'm currently doing this with repeated called to stringByReplacingOccurencesOfString:withString::

NSString *s1 = @"abcdabcd";
NSString *s2 = [[s1 stringByReplacingOccurencesOfString:@"a" withString:@"z"]
                 stringByReplacingOccurencesOfString:@"b" withString:@"z"];

What's a better way? I didn't find any similar methods that take an array of strings to replace.

Upvotes: 2

Views: 229

Answers (2)

Michael Dautermann
Michael Dautermann

Reputation: 89509

There's also NSMutableString's replaceOccurrencesOfString:withString:options:range: method (so you don't have to create a new NSString object for every replacement call you want to make). Documentation linked for you.

Upvotes: 3

Nicolas Bachschmidt
Nicolas Bachschmidt

Reputation: 6505

You can use regular expressions:

NSString *s2 =
[s1 stringByReplacingOccurrencesOfString:@"[ab]"
                              withString:@"z"
                                 options:NSRegularExpressionSearch
                                   range:NSMakeRange(0, s1.length)];

Upvotes: 6

Related Questions