0

I am trying to search for a string within an array, but I only want to search the last five objects in the array for the string.

I have been fiddling with every parameter I can find on NSRange to no avail.

I would post some example code, but I can't even get out the line I need, whether its through introspection, enumeration, or just some NSRange call that I missed.

3 Answers 3

2

If your array elements are strings that you searched for, you can directly check the array as follows:

if ([yourArray containsObject:yourString])
{
     int index = [yourArray indexOfObject:yourString];

     if (index>= yourArray.count-5)
     {
          // Your string matched
     }
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1 Nice solution. Duplicate objects might however cause trouble.
1

I like indexesOfObjectsWithOptions:passingTest: for this. Example:

    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);

Comments

0

Try this :-

//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
        }
    }

Hope this helps you!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.