获取 NSMutableArray 中最后一个重复字符串的索引
Get index of last repeated string in NSMutableArray
我有一个包含多个重复字符串的 NSMutableArray,我正在尝试获取最后一个字符串索引。
NSMutableArray *arrWithRepeatedStrings=[[NSMutableArray alloc]initWithObjects:@"iOS",@"apple",@"iOS",@"apple",@"apple",@"iOS", nil];
这里 iOS
和 apple
是我的数组中重复的字符串。我认为这是可能的,并且正在走向它。谁能帮帮我
反方向枚举可以得到字符串最后一次出现的索引。使用下面的代码。如果你想要它的索引而不是 @"apple"
.
,你可以将匹配字符串更改为 @"iOS"
NSMutableArray *arrWithRepeatedStrings=[[NSMutableArray alloc]initWithObjects:@"iOS",@"apple",@"iOS",@"apple",@"apple",@"iOS", nil];
NSInteger index = [arrWithRepeatedStrings indexOfObjectWithOptions:NSEnumerationReverse passingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
if([obj isEqualToString: @"apple"])
return YES;
else
return NO;
}];
我理解您想要数组中不止一次的最后一个对象的索引的问题。这与@Gandalf 的解决方案完全不同,所以这是我的看法:
NSInteger index = [array indexOfObjectWithOptions:NSEnumerationReverse
passingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
BOOL match = [arrWithRepeatedStrings indexOfObject:obj] != idx;
if (match) *stop = YES;
return match;
}];
我有一个包含多个重复字符串的 NSMutableArray,我正在尝试获取最后一个字符串索引。
NSMutableArray *arrWithRepeatedStrings=[[NSMutableArray alloc]initWithObjects:@"iOS",@"apple",@"iOS",@"apple",@"apple",@"iOS", nil];
这里 iOS
和 apple
是我的数组中重复的字符串。我认为这是可能的,并且正在走向它。谁能帮帮我
反方向枚举可以得到字符串最后一次出现的索引。使用下面的代码。如果你想要它的索引而不是 @"apple"
.
@"iOS"
NSMutableArray *arrWithRepeatedStrings=[[NSMutableArray alloc]initWithObjects:@"iOS",@"apple",@"iOS",@"apple",@"apple",@"iOS", nil];
NSInteger index = [arrWithRepeatedStrings indexOfObjectWithOptions:NSEnumerationReverse passingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
if([obj isEqualToString: @"apple"])
return YES;
else
return NO;
}];
我理解您想要数组中不止一次的最后一个对象的索引的问题。这与@Gandalf 的解决方案完全不同,所以这是我的看法:
NSInteger index = [array indexOfObjectWithOptions:NSEnumerationReverse
passingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
BOOL match = [arrWithRepeatedStrings indexOfObject:obj] != idx;
if (match) *stop = YES;
return match;
}];