在数组中搜索 NSRange 的字符串



>我正在尝试在数组中搜索字符串,但我只想在数组中的最后五个对象中搜索字符串。

我一直在摆弄我在 NSRange 上能找到的每个参数,但无济于事。

我会发布一些示例代码,但我什至无法得到我需要的行,无论是通过内省、枚举,还是只是我错过的一些 NSRange 调用。

如果你的数组元素是你搜索的字符串,你可以直接检查数组,如下所示:

if ([yourArray containsObject:yourString])
{
     int index = [yourArray indexOfObject:yourString];
     if (index>= yourArray.count-5)
     {
          // Your string matched
     }
}
我喜欢

indexesOfObjectsWithOptions:passingTest:。例:

    NSArray *array = @[@24, @32, @126, @1, @98, @16, @67, @42, @44];
    // run test block on each element of the array, starting at the end of the array
    NSIndexSet *hits = [array indexesOfObjectsWithOptions:NSEnumerationReverse passingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        // if we're past the elements we're interested in
        // we can set the `stop` pointer to YES to break out of
        // the enumeration
        if (idx < [array count] - 5) {
            *stop = YES;
            return NO;
        }
        // do our test -- if the element matches, return YES
        if (40 > [obj intValue]) {
            return YES;
        }
        return NO;
    }];
    // indexes of matching elements are in `hits`
    NSLog(@"%@", hits);

试试这个:-

//Take only last 5 objects
NSRange range = NSMakeRange([mutableArray1 count] - 5, 5);
NSMutableArray *mutableArray2 = [NSMutableArray arrayWithArray:
                                  [mutableArray1 subarrayWithRange:range]];
//Now apply search logic on your mutableArray2
for (int i=0;i<[mutableArray2 count];i++)
    {
        if ([[mutableArray2 objectAtIndex:i] isEqualToString:matchString])
        {
            //String matched
        }
    }

希望对您有所帮助!

最新更新