Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

the ev

macrumors newbie
Original poster
Jun 14, 2008
9
0
Hello,

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!!
 

Sbrocket

macrumors 65816
Jun 3, 2007
1,250
0
/dev/null
Code:
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.
 

the ev

macrumors newbie
Original poster
Jun 14, 2008
9
0
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!
 

lee1210

macrumors 68040
Jan 10, 2005
3,182
3
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.

-Lee

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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.