How to search by both first name and last name

折月煮酒 提交于 2021-01-28 12:38:33

问题


I am doing a search screen (to search list of names) on my iphone app , where i need to search by both first name and last name

say my search tableview contains names like follows

Ravi Kiran 
sujay huilgol
harry potter 

my search is working for only first name i.e if i search for Ra it ill show Ravi Kiran but when i search for Kiran its not displaying Ravi Kiran

my filterContentForSearchText is like this

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    [self.arrSearhResults removeAllObjects]; // First clear the filtered array.

    // Search the main list for Usenames whose type matches searchText; add items that match to the filtered array.

    for(NSString * strUserName in arrUserInfo )
    {
        NSComparisonResult result = [strUserName compare:searchText options:(NSLiteralSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
        if (result == NSOrderedSame)
        {
            // Update the filtered array based on the search text and scope.
            [self.arrSearhResults addObject:strUserName];
            //NSLog(@"arrSearhResults %@",arrSearhResults);
        }
    }

}

could anybody help me out please..... thanx in advance!


回答1:


use rangeOfString to search whole string

 for(NSString * strUserName in arrUserInfo )
{
  NSRange range = [strUserName rangeOfString:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)];
  if (range.length > 0)
  {
    [self.arrSearhResults addObject:strUserName];
  }
}



回答2:


Try this:

for(NSString * strUserName in arrUserInfo )
{
  NSRange titleResultsRange = [[NSString stringWithFormat:@"%@",strUserName] rangeOfString:searchText options:NSCaseInsensitiveSearch];
    if (titleResultsRange.length){
        [self.arrSearhResults addObject:[self.contacts objectAtIndex:i]];
    }
}



回答3:


NSArray *array = [[NSArray alloc] initWithObjects:@"Ravi Kiran", @"sujay huilgol", nil];
for (NSString* name in array)
{
    if ([name rangeOfString:@"Kiran"].location != NSNotFound)
        NSLog(@"%@", name);
}


来源:https://stackoverflow.com/questions/12634493/how-to-search-by-both-first-name-and-last-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!