user2523879
user2523879

Reputation: 39

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

Upvotes: 1

Views: 918

Answers (2)

Mick MacCallum
Mick MacCallum

Reputation: 130193

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.

Upvotes: 3

demonofthemist
demonofthemist

Reputation: 4199

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];
}

Upvotes: 0

Related Questions