所以我基本上有一系列单词和短语。其中一些包含诅咒。我想创建一个方法来自动扫描数组中的每个单元以查找诅咒。如果它没有诅咒,请将其添加到新数组中。
我意识到我可以用一堆来做到这一点if
/else if
声明和rangeOfString
方法,但令我震惊的是我还没有找到一种方法NSString
它将同时搜索一堆单词。
有没有我可能忽略的东西可以用来扫描单个字符串以查找子字符串数组?
例如:
如果我有一系列短语,例如:
@[@"hey how are you",
@"what is going on?",
@"whats up dude?",
@"do you want to get chipotle?"]
我希望能够扫描然后派生一个新数组,该数组不包含以下数组中的任何单词:
@[@"you", @"hey"]
如果它是一个相当小的列表,只需迭代它检查每个单词。
如果它相当大,请将“坏话”放在一个NSOrderedSet
然后使用方法:containsObject:
.
如果要检查的单词数量不少,也可以将要检查的单词放在一个NSSet
以及另一篇文章中的“脏话”NSSet
并使用方法:intersectsSet:
.
Example:
NSArray *stringsToCheck = @[@"hey how are you", @"what is going on?", @"whats up dude?", @"do you want to get chipotle?"];
NSSet *badWords = [NSSet setWithArray:@[@"how", @"dude", @"yes"]];
for (NSString *line in stringsToCheck) {
NSSet *checkWords = [NSSet setWithArray:[line componentsSeparatedByString:@" "]];
NSLog(@"checkWords: %@", checkWords);
if ([checkWords intersectsSet:badWords]) {
NSLog(@"checkWords contains a bad word in: '%@'", [[checkWords allObjects] componentsJoinedByString:@" "]);
// Now search for the specific bad word if necessary.
}
}
NSLog 输出:
checkWords 中包含坏词:“you how are hey”
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)