Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 378
Matt Sephton Avatar asked Apr 03 '09 13:04

Matt Sephton


People also ask

How to replace string in Objective C?

To replace a character in objective C we will have to use the inbuilt function of Objective C string library, which replaces occurrence of a string with some other string that we want to replace it with.


1 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.

like image 113
Nicholas Riley Avatar answered Sep 22 '22 09:09

Nicholas Riley