简体   繁体   English

如何获取以ios中的字母开头的数组元素的索引?

[英]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"? 如何获取以“a”开头的数组元素的索引?

In the case if it is 0 and 1, how to get both the values? 在它是0和1的情况下,如何获得这两个值? please help 请帮忙

I would use NSArray's indexesOfObjectsPassingTest: method to handle this. 我会使用NSArray的indexesOfObjectsPassingTest:方法来处理这个问题。 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". 在这种情况下,字符串是否以字母“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. 从那里,如果您宁愿将这些索引存储在一个数组中,您只需枚举该集合,并将包含索引的NSNumbers添加到一个新数组中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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