2

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.

2 Answers 2

6

You can use regular expressions:

NSString *s2 =
[s1 stringByReplacingOccurrencesOfString:@"[ab]"
                              withString:@"z"
                                 options:NSRegularExpressionSearch
                                   range:NSMakeRange(0, s1.length)];
Sign up to request clarification or add additional context in comments.

1 Comment

(If you're targeting OS X 10.7+/iOS 4.0+.)
3

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.

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.