比如说,我有词汇表(大约 100000 个单词)和单词(“inputstring”)。所以:
我需要从“inputstring”生成所有单词,如“input”、“string”、“put”、“strinpg”等。然后我需要在我的词汇表中检查它们。你能说出什么好的算法吗?因为我只知道:
- 在第 1 步递归搜索所有可能的组合
- 使用
NSPredicates
在我的词汇表中过滤它们。
最佳答案
我尝试使用 NSRegularExpression
,因为 CoreData 和 NSPredicate
似乎可以管理它们,但我无法找到可行的解决方案(可能与我在 Regex 方面的专业知识无关,但是可能是一个线索)。我也尝试使用 NSCharacterSet
,但它不能说出现的次数是正确的..
这可能不是更性感的方式,但是,您可以这样做:
NSString *searchedWord = @"inputString";
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(NSString *evaluatedObject, NSDictionary *bindings) {
for (NSUInteger index = 0; index < [evaluatedObject length]; index++)
{
NSString *subString = [evaluatedObject substringWithRange:NSMakeRange(index, 1)];
NSUInteger numberOfOccurrencesInSearchWord = [self occurrencesOfSubString:subString inString:searchedWord];
NSUInteger numberOfOccurrencesInCurrentWord = [self occurrencesOfSubString:subString inString:evaluatedObject];
if (numberOfOccurrencesInCurrentWord > numberOfOccurrencesInSearchWord)
return FALSE;
}
return TRUE;
}];
//Apply this predicate to your fetch
我将 occurrencesOfSubString:inString:
放在类中,但它可能是 NSString
上的一个类别。如果您更喜欢 NSRegularExpression
,也可以使用 rangeOfString:option:range
进行循环。 Source of the code (稍作修改)
-(NSUInteger)occurrencesOfSubString:(NSString *)subString inString:(NSString *)string
{
NSUInteger numberOfMatches = 0;
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:subString
options:NSRegularExpressionCaseInsensitive error:&error];
if (!error)
numberOfMatches = [regex numberOfMatchesInString:string options:0 range:NSMakeRange(0, [string length])];
return numberOfMatches;
}
注意:为了避免过多的循环,您可能需要剥离 evaluatedObject
以便不检查重复的值。
例如,如果 evaluatedObject = @"aaa"
,它将查找 3 次“a”。因此,删除其中的重复值可能 会提高速度。这是一个 solution .
所以代码将在谓词 block 中:
NSString *evaluatedWithoutRepeat = [evaluatedObject removeDuplicatedCharacters];
for (NSUInteger index = 0; index <= [evaluatedWithoutRepeat length]; index ++)
{
NSString *subString = [evaluatedWithoutRepeat substringWithRange:NSMakeRange:(index,1)];
//The rest would be the same.
}
工作测试:
NSArray *testValues = @[@"inputString",
@"input",
@"string",
@"put",
@"strinpg",
@"Stringpg",
@"stringNOTWANTED"];
NSLog(@"AllValues: %@", testValues);
NSLog(@"Test: %@", [testValues filteredArrayUsingPredicate:predicate]);
输出:
> AllValues: (
inputString,
input,
string,
put,
strinpg,
Stringpg,
stringNOTWANTED
)
> Test: (
inputString,
input,
string,
put,
strinpg
)
关于ios - 如何在 ios 中搜索输入字符串中的所有单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31526878/