How to replace a character that exists independently rather than with other characters in an NSString?

202 Views Asked by At

Ok lets suppose i've got this string:

R RATS ARE FAR

I want to replace the independent R with an X so to make:

X RATS ARE FAR

I've tried stringByReplacingOccurrencesOfString but that replaces all R's to X's. One way to accomplish it is to check if there's a space before and after the letter, which would mean its independent and then go for the kill, but this approach seems so lame. Also the string is dynamic and so are the position of R's.

2

There are 2 best solutions below

1
On BEST ANSWER

I'm assuming here that words can be surrounded by just about any non-alphanumeric character, right? (Otherwise you'd just replace @" R " with " X ", plus special cases for leading/trailing occurrences)


One way to do it would be to use RegexKitLite's

[string replaceOccurrencesOfRegex:@"\bR\b" withString:@"X"];

(\b denotes word *b*oundaries in PCRE-style regular expressions)


And then there is CFStringTokenizer (search linked documentation for kCFStringTokenizerUnitWordBoundary), which might be of help, alternatively.

9
On

I would do it this way:

NSString *statement = @"R RATS ARE FAR";
statement = [statement stringByReplacingOccurrencesOfString:@" R " withString:@" X "];
// now check if the string starts with R + space
if ([statement hasPrefix:@"R "])
    statement = [statement stringByReplacingOccurrencesOfString:@"R " withString:@"X " options:0 range:NSMakeRange(0,2)];
// now check the end
if ([statement hasSuffix:@" R"])
   statement = [statement stringByReplacingOccurrencesOfString:@" R" withString:@" X" options:0 range:NSMakeRange([statement length] - 2, 2)];

And if you are planning to a lot of replacement in this string, you should use NSMutableString.