我目前正在使用以下算法搜索我的iPhone应用程序:
NSRange range = [entry.englishEntry rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(range.location != NSNotFound)
{
[self.filteredListContent addObject:entry];
}
问题在于,当我搜索像'废话'这样的单词时,我也会得到像'scrap'这样无关紧要的单词的结果。我对NSRange不熟悉,那么搜索整个单词的搜索算法是什么?
答案 0 :(得分:3)
我刚刚通过在NSString上添加一个简单类别来进行单词边界搜索来解决这个问题。这是代码:
@interface NSString (FullWordSearch)
// Search for a complete word. Does not match substrings of words. Requires fullWord be present
// and no surrounding alphanumeric characters.
- (BOOL)containsFullWord:(NSString *)fullWord;
@end
@implementation NSString (FullWordSearch)
- (BOOL)containsFullWord:(NSString *)fullWord {
NSRange result = [self rangeOfString:fullWord];
if (result.length > 0) {
if (result.location > 0 && [[NSCharacterSet alphanumericCharacterSet] characterIsMember:[self characterAtIndex:result.location - 1]]) {
// Preceding character is alphanumeric
return NO;
}
if (result.location + result.length < [self length] && [[NSCharacterSet alphanumericCharacterSet] characterIsMember:[self characterAtIndex:result.location + result.length]]) {
// Trailing character is alphanumeric
return NO;
}
return YES;
}
return NO;
}
@end
答案 1 :(得分:2)
是的,你可以用文字搜索。您需要先将字符串拆分为组件。然后遍历每个并比较它们。
类似的东西:
NSArray *words = [entry.english componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; for (NSString *word in words) { NSComparisonResult result = [word compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])]; if (result == NSOrderedSame) { [self.filteredListContent addObject:entry]; break; } }
答案 2 :(得分:0)
不是查找字符串的范围,而是进行不区分大小写的比较并检查结果是否为NSOrderedSame
if([entry.english caseInsensitiveCompare:searchText] == NSOrderedSame){
[self.filteredListContent addObject:entry];
}
这会将文本与整个单词进行比较,而不只是查找范围。
答案 3 :(得分:0)
现在我将它变得更通用,通过使用此代码,您可以搜索目标字符串
之间的任何字符串 NSString * strName =[entry.english lowercaseString];
if ([strName rangeOfString:[searchText lowercaseString]].location != NSNotFound) {
[self.filteredListContent addObject:entry];}