Reputation: 19737
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
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
Reputation: 6505
You can use regular expressions:
NSString *s2 =
[s1 stringByReplacingOccurrencesOfString:@"[ab]"
withString:@"z"
options:NSRegularExpressionSearch
range:NSMakeRange(0, s1.length)];
Upvotes: 6