简体   繁体   中英

how to get indexes of an array element starting with a letter in ios?

I want to get indexes of an array starting with particular letter, Example: i have an array

NSArray *arr = @[@"apple", @"aghf", @"chg", @"dee", @"ijh", @"inbv", @"khh"];

how to get the indexes of array elements starting with "a"?

In the case if it is 0 and 1, how to get both the values? please help

I would use NSArray's indexesOfObjectsPassingTest: method to handle this. It will give you an index set containing all of the indexes that pass what ever test you specify. In this case, whether or not the string is prefixed with the letter "a".

NSArray *array = @[@"apple", @"aghf", @"chg", @"dee", @"ijh", @"inbv", @"khh"];

NSIndexSet *indexes = [array indexesOfObjectsPassingTest:^BOOL(NSString *string, NSUInteger idx, BOOL *stop) {
    return [string hasPrefix:@"a"];
}];

NSLog(@"%@",indexes);

From there, if you'd rather store these indexes in an array, all you have to do is enumerate the set, and add NSNumbers containing the indexes into a new array.

Use Following code:

text = @"a";        
filterArray = [[NSMutableArray alloc] init];
for(int i=0; i<names.count; i++)
{
     NSString *obj = names[i];
     NSRange nameRange = [obj rangeOfString:text options:NSCaseInsensitiveSearch];
     if(nameRange.location != NSNotFound && nameRange.location == 0)
          [responseArray addObject:obj];
}

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