ios - 将 NSString 与 NSArray 中的单词进行匹配的最快方法

标签 ios objective-c nsstring nsarray

我有一个包含超过 2000 个单词的 NSArray 以及同样长的分数列表。我想迭代用户输入的句子/文本文件中的每个单词,并为每个单词获取列表中存在的每个单词的分数。以下是我目前正在执行此操作的方法,但我怀疑这是最快的方法。我的问题是是否有更快的方法来完成我想要完成的任务?

  [sentence enumerateSubstringsInRange:NSMakeRange(0, [sentence length])
                               options:NSStringEnumerationByWords | NSStringEnumerationLocalized
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){
                                NSUInteger index=[wordArray indexOfObject:substring];
                                if (index!=NSNotFound) {
                                    double score=scoreArray[index];
                                    do something with the score
                                        }
                            }];

最佳答案

2000 是一个很小的数组。在您深入之前,read Knuth's view about premature optimization 。当你发现明显的问题后,努力加快速度。如果您达到了这一点,这听起来确实是 NSMutableDictionary 的一个很好的应用程序。它可以有 2k 个单词键,执行(类似 NSSet)查找,并保留关联值(应用程序中的“分数”)。

因此对于文件中的每个单词:

NSNumber *score = self.dictionary[word];
if (score) {
    NSNumber *newScore = // whatever
    self.dictionary[word] = newScore;
}

如果顺序很重要,您可以随时进行事后排序。

关于ios - 将 NSString 与 NSArray 中的单词进行匹配的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25395717/

相关文章:

iphone - 横向时如何让 Interface Builder 中的两个 UITextView 正确对齐?

objective-c - pushViewController 占用过多显示 View

ios - UIWebView 委托(delegate)方法 shouldStartLoadWithRequest : equivalent in WKWebView?

iphone - 整个应用程序中的单个动画 UIImageView 背景

objective-c - 在 iOS 中使用 RestKit 解析 unix 时间戳

ios - 将分配的对象分配给某些未分配的对象会导致内存泄漏吗?

Cocoa - 删除字符串中的子字符串之前的所有字符

objective-c - Objective-C stringWithCString "Method cache corrupted"

objective-c - 带有表情符号的 NSString

iphone - iPhone应用程序在添加UISwitch时崩溃