Replace multiple characters in a string in Objective-C?

In PHP I can do this:

$new = str_replace(array('/', ':', '.'), '', $new);

...to replace all instances of the characters / : . with a blank string (to remove them)

Can I do this easily in Objective-C? Or do I have to roll my own?

Currently I am doing multiple calls to stringByReplacingOccurrencesOfString:

strNew = [strNew stringByReplacingOccurrencesOfString:@"/" withString:@""];
strNew = [strNew stringByReplacingOccurrencesOfString:@":" withString:@""];
strNew = [strNew stringByReplacingOccurrencesOfString:@"." withString:@""];

Thanks,
matt


Solution 1:

A somewhat inefficient way of doing this:

NSString *s = @"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
NSLog(@"%@", s); // => foobarbazfoo

Look at NSScanner and -[NSString rangeOfCharacterFromSet: ...] if you want to do this a bit more efficiently.

Solution 2:

There are situations where your method is good enough I think matt.. BTW, I think it's better to use

[strNew setString: [strNew stringByReplacingOccurrencesOfString:@":" withString:@""]];

rather than

strNew = [strNew stringByReplacingOccurrencesOfString:@"/" withString:@""];

as I think you're overwriting an NSMutableString pointer with an NSString which might cause a memory leak.

Solution 3:

Had to do this recently and wanted to share an efficient method:

(assuming someText is a NSString or text attribute)

NSString* someText = @"1232342jfahadfskdasfkjvas12!";

(this example will strip numbers from a string)

[someText stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [someText length])];

Keep in mind that you will need to escape regex literal characters using Obj-c escape character:

(obj-c uses a double backslash to escape special regex literals)

...stringByReplacingOccurrencesOfString:@"[\\\!\\.:\\/]" 

What makes this interesting is that NSRegularExpressionSearch option is little used but can lead to some very powerful controls:

You can find a nice iOS regex tutorial here and more on regular expressions at regex101.com