String replacement in Objective-C String replacement in Objective-C ios ios

String replacement in Objective-C


You could use the method

- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target                                         withString:(NSString *)replacement

...to get a new string with a substring replaced (See NSString documentation for others)

Example use

NSString *str = @"This is a string";str = [str stringByReplacingOccurrencesOfString:@"string"                                     withString:@"duck"];


NSString objects are immutable (they can't be changed), but there is a mutable subclass, NSMutableString, that gives you several methods for replacing characters within a string. It's probably your best bet.


If you want multiple string replacement:

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