Replace multiple characters in a string in Objective-C?

Viewed 78755

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

8 Answers

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.

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.

Related