获取和替换字符串中特定单词的最佳方法是什么?
例如我有
NSString * currentString = @"one {two}, thing {thing} good";
现在我需要找到每个{currentWord}
并为其应用函数
[self replaceWord:currentWord]
然后用函数的结果替换 currentWord
-(NSString*)replaceWord:(NSString*)currentWord;
以下示例展示了如何使用NSRegularExpression
and enumerateMatchesInString
完成任务。我刚刚用过uppercaseString
作为替换单词的函数,但您可以使用replaceWord
方法还有:
EDIT:如果替换的单词是,我的答案的第一个版本无法正常工作
与原文一样短或长(感谢 Fabian Kreiser 注意到这一点!)。
现在它应该在所有情况下都能正常工作。
NSString *currentString = @"one {two}, thing {thing} good";
// Regular expression to find "word characters" enclosed by {...}:
NSRegularExpression *regex;
regex = [NSRegularExpression regularExpressionWithPattern:@"\\{(\\w+)\\}"
options:0
error:NULL];
NSMutableString *modifiedString = [currentString mutableCopy];
__block int offset = 0;
[regex enumerateMatchesInString:currentString
options:0
range:NSMakeRange(0, [currentString length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
// range = location of the regex capture group "(\\w+)" in currentString:
NSRange range = [result rangeAtIndex:1];
// Adjust location for modifiedString:
range.location += offset;
// Get old word:
NSString *oldWord = [modifiedString substringWithRange:range];
// Compute new word:
// In your case, that would be
// NSString *newWord = [self replaceWord:oldWord];
NSString *newWord = [NSString stringWithFormat:@"--- %@ ---", [oldWord uppercaseString] ];
// Replace new word in modifiedString:
[modifiedString replaceCharactersInRange:range withString:newWord];
// Update offset:
offset += [newWord length] - [oldWord length];
}
];
NSLog(@"%@", modifiedString);
Output:
one {--- TWO ---}, thing {--- THING ---} good
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)