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

标签 objective-c string cocoa cocoa-touch nsstring

我想遍历 NSString 并对每个具有特定条件的单词调用自定义函数(例如,“有 2 个‘L’s”)。我想知道最好的方法是什么。我应该使用查找/替换模式吗? block ?

-(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:] 以及 NSStringEnumerationByWordsNSStringEnumerationLocalized。列出的所有其他方法都使用一种方法来识别可能不适合语言环境或不符合系统定义的单词。例如,用逗号而不是空格分隔的两个单词(例如“foo,bar”)不会被任何其他答案视为单独的单词,但它们在 Cocoa TextView 中。

[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] 的东西。

关于objective-c - 对 NSString 中的每个单词调用一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11171051/

相关文章:

ios - 将 firebase 框架添加到 ios 项目时出现链接器错误

javascript - 生成随机字符串并检查数据库以确保不重复

ios - 如何使用 Objective C 将 UIObjects 从一个类重用到多个类?

ios - Firebase - 获取数据,受日期限制

string - 如何在 Scala 中简洁地用默认字符串替换空字符串(或 null)

c - 从特定索引 C 读取 char*

objective-c - 如何有效地展平 NSOutlineView?

objective-c - NSPathControl 和自动布局

objective-c - 如何在 NSOutlineView 中制作带有渐变背景的标题行?

ios - UITableViews 和 UITableViewCells