如何在ios中获取以字母开头的数组元素的索引?
我想得到一个以特定字母开头的数组的索引, 示例:我有一个数组如何在ios中获取以字母开头的数组元素的索引?,ios,objective-c,nsarray,Ios,Objective C,Nsarray,我想得到一个以特定字母开头的数组的索引, 示例:我有一个数组 NSArray*arr=[@“苹果”、“aghf”、“chg”、“dee”、“ijh”、“inbv”、“khh”] 如何获取以“a”开头的数组元素的索引 如果是0和1,如何获取这两个值?请帮助我将使用NSArray的indexesOfObjectsPassingTest:方法来处理此问题。它将为您提供一个索引集,其中包含通过您指定的任何测试的所有索引。在这种情况下,不管字符串是否以字母“a”作为前缀 从这里开始,如果您希望将这些索引存
NSArray*arr=[@“苹果”、“aghf”、“chg”、“dee”、“ijh”、“inbv”、“khh”]代码>
如何获取以“a”开头的数组元素的索引
如果是0和1,如何获取这两个值?请帮助我将使用NSArray的indexesOfObjectsPassingTest:
方法来处理此问题。它将为您提供一个索引集,其中包含通过您指定的任何测试的所有索引。在这种情况下,不管字符串是否以字母“a”作为前缀
从这里开始,如果您希望将这些索引存储在一个数组中,则只需枚举集合,并将包含索引的NSNumbers添加到一个新数组中。使用以下代码:
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];
}
text=@“a”;
filterArray=[[NSMutableArray alloc]init];
对于(int i=0;iYou可以将测试简化为[string hasPrefix:@“a”]
。将块声明为^BOOL(NSString*string,NSUInteger idx,BOOL*stop)
会使强制转换过时。
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];
}