简体   繁体   中英

How can I compare case insensitive NSRange ?

I wrote a method to search for people in address book, and I want the method to be able to find "john bigs" even if I call the method [someAdressBook searchName:@"joh"]; .

My method works for full names, but Im having issues in the partial names, this is my code:

-(NSMutableArray *) searchName:(NSString *) someName{

    NSRange range;

    NSMutableArray *results = [[NSMutableArray alloc] init];

    for (AddressCards *addressCard in book)
    {
        if (someName != nil && [someName caseInsensitiveCompare:addressCard.name] == NSOrderedSame)
            [results addObject:addressCard.name];

        else {
            range = [addressCard.name rangeOfString:someName];
            if (range.location != NSNotFound)
            [results addObject:addressCard.name];
        }
    }

    NSLog(@"%@", results);

    return results;
}

Please help me get this right.

You can do the search in a case-insensitive manner using -[NSString rangeOfString:options:], so you can do it in one step:

for (AddressCards *addressCard in book)
{
    if ([addressCard.name rangeOfString:someName options:NSCaseInsensitiveSearch].location != NSNotFound)
    {
        [results addObject:addressCard.name];
    }
}

You can use NSPredicate like this:

-(NSMutableArray *) searchName:(NSString *) someName {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY addressCard.name CONTAINS[c] %@", someName];
    return [NSMutableArray arrayWithArray:[book filteredArrayUsingPredicate:predicate]];
}

The trick here is the [c] . This is equivalent to case insensitive.

Notice that I'm supposing that book is of NSArray type, if it is of NSMutableArray , using predicate will filter the "original" array.

you could use this

BOOL containsName = [[addressCard.name lowercaseString] containsSubstring: [someName lowercaseString]];
if(containsName)
    [results addObject:addressCard.name];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM