我扩展了使用It
设置的黑名单单词,以发现某些单元测试现在失败了。
我没有注意到笔记中的I
现在也已被排除,因为它与It
匹配,这不是我想要的。
notes = @"I was out with Jenny for dinner. It was raining all night.";
NSString * const BLACKLISTEDWORDS = @"in,it,It";
NSArray *words = [notes componentsSeparatedByString:@" "];
for (NSString *word in words) {
if([BLACKLISTEDWORDS rangeOfString:word].location == NSNotFound]) {
}
}
有没有更好的方法来创建黑名单方法?
解决方案: 马特解决方案工作正常。要将其捕获为此解决方案的代码:
NSSet *blackList = [NSSet setWithArray:[BLACKLISTEDWORDS componentsSeparatedByString:@","]];
for (NSString *word in words) {
if (![blackList containsObject:word]) {
}
}
答案 0 :(得分:1)
问题在于,您只是将notes
与单个字符串的单词进行比较,即@"in,it,It"
。所以“我”将成功,“n”将成功,“n,i”将成功,等等。这根本不是你想要的。
相反,将列入黑名单的单词分解为单个单词。将它们分成一个集合(NSSet),并查看notes
的每个单词是否是该集合的成员。