Ok lets suppose i've got开发者_如何学C 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.
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.
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
.
精彩评论