Thursday, April 14, 2011

String replacement in Objective-C

What is the best way to replace a character is a string in Objective-C for iPhone SDK?

From stackoverflow
  • 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.

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

0 comments:

Post a Comment