Q:

stringByReplacingOccurrencesOfString replacing composites of longer words

When using stringByReplacingOccurrencesOfString, it seems to replace words inside words. So for example, 
The house was held together by...

replacing occurrences of 'the' with 'A' will result in
A house was held togeAr by...

How can I avoid this? I know I could add whitespace on either side of the word being replaced to ensure it's not part of a longer word, however this doesn't work in all cases, specifically where the word being replaced is the first or last word in the sentence (that is, when white space isn't on both sides). 

A:

You should use an NSRegularExpression with the pattern \bthe\b where \b indicates a word boundary.
NSString *input = @"The house was held together by...";
NSString *string = @"the";
NSString *replacement = @"A";

NSString *pattern = [NSString stringWithFormat:@"\\b%@\\b", string];
NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
NSString *result = [regex stringByReplacingMatchesInString:input options:0 range:NSMakeRange(0, input.length) withTemplate:replacement];

NSLog(@"%@", result);
// A house was held together by...

