您应该使用NSRegularExpression
with 表示单词边界的\bthe\b
模式\b
。
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...