String replacement in Objective-C

4thSpace picture 4thSpace · Mar 20, 2009 · Viewed 258k times · Source

How to replace a character is a string in Objective-C?

Answer

epatel picture epatel · Mar 20, 2009

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"];