簡體   English   中英

stringByReplacingOccurrencesOfString替換較長單詞的復合詞

[英]stringByReplacingOccurrencesOfString replacing composites of longer words

當使用stringByReplacingOccurrencesOfString ,似乎替換了單詞中的單詞。 例如

The house was held together by...

將“ the”的出現替換為“ A”將導致

A house was held togeAr by...

如何避免這種情況? 我知道我可以在要替換的單詞的兩邊添加空格,以確保它不是較長單詞的一部分,但是,這並非在所有情況下都有效,特別是要替換的單詞是句子中的第一個或最后一個單詞時(也就是說,兩邊都沒有空格時)。

您應該將NSRegularExpression\\bthe\\b NSRegularExpression \\bthe\\b模式NSRegularExpression使用,其中\\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...

對於更復雜的替換操作,可以使用NSRegularExpression 您可以搜索類似(^| )the($| )並替換匹配項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM