对 NSString 中的每个单词调用一个方法

2024-04-19

我想循环遍历NSString并对每个具有特定条件的单词调用自定义函数(例如,“has 2 'L's”)。我想知道解决这个问题的最佳方法是什么。我应该使用查找/替换模式吗?块?

-(NSString *)convert:(NSString *)wordToConvert{
    /// This I have already written
    Return finalWord;
}

-(NSString *) method:(NSString *) sentenceContainingWords{
    // match every word that meets the criteria (for example the 2Ls) and replace it with what convert: does. 
}

要枚举字符串中的单词,您应该使用-[NSString enumerateSubstringsInRange:options:usingBlock:] with NSStringEnumerationByWords and NSStringEnumerationLocalized。列出的所有其他方法都使用可能不适合语言环境或不对应于系统定义的单词识别方法。例如,由逗号分隔但不是空格的两个单词(例如“foo,bar”)不会被任何其他答案视为单独的单词,但它们在 Cocoa 文本视图中。

[aString enumerateSubstringsInRange:NSMakeRange(0, [aString length])
                            options:NSStringEnumerationByWords | NSStringEnumerationLocalized
                         usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){
    if ([substring rangeOfString:@"ll" options:NSCaseInsensitiveSearch].location != NSNotFound)
        /* do whatever */;
}];

据记录-enumerateSubstringsInRange:options:usingBlock:,如果您在可变字符串上调用它,则可以安全地改变正在枚举的字符串enclosingRange。所以,如果你想替换匹配的单词,你可以用类似的东西[aString replaceCharactersInRange:substringRange withString:replacementString].

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

对 NSString 中的每个单词调用一个方法 的相关文章

随机推荐