Replace Characters in NSString

Discussion in 'Mac Programming' started by the ev, Jun 14, 2008.

  1. macrumors newbie

    Jun 14, 2008

    I've what I think a pretty n00b question, but I can't seem to make heads or tails of anything I've been able to find online on the subject (either that or I'm just brain dead from trying).

    Anywho, I want to be able to take a NSString and replace all occurances of a single character with another character.

    So if my original NSString contained: "I'm a noob at Objective-C."

    And I wanted all "o"s to be "0"s, then I would get: "I'm a n00b at 0bjective-C."

    Does anyone know how I could do this? Thanks for the help!!
  2. macrumors 65816


    Jun 3, 2007
    NSString *firstString = @"I'm a noob at Objective-C", *finalString;
    finalString = [[firstString stringByReplacingOccurancesOfString:@"O" withString:@"0"] stringByReplacingOccurancesOfString:@"o" withString:@"0"];
    That's the "easiest" way to do it, I suppose, but there are tons of ways to reach the same result with string operations, and I'm sure someone will come along and mention the "optimized" way of doing this. That certainly works though.

    Make sure you take a look through Xcode's Documentation window in the future. You won't get anywhere without it using it.
  3. thread starter macrumors newbie

    Jun 14, 2008
    Thank you; yes, I did try to find something in the XCode documentation, but my Google searches led me to try and accomplish this with a NSMutableString, and I couldn't figure out how to cast (right terminology?) my NSString as a NSMutableString. Didn't occur to me that there might be a method in NSString to do just that.

    Is there anyway that you know of to do multiple replacements (more than the two listed in your example) in one pass? Or if I could make the substitutions case-insensitive?

    Thanks for the help!
  4. macrumors 68040


    Jan 10, 2005
    Dallas, TX
    Might be better, but not by much, NSMutableString:replaceOccurrencesOfString will get your the same result, but "in place". NSString, like NSArray, is not mutable. The functions provided create new NSStrings. That's fine, but perhaps a tiny bit inefficient.


    Edit: Too slow it looks like...

    NSMutableString is a subclass of NSString, so you can do an assignment, use it as a parameter to something taking an NSString, etc.

Share This Page