2

I have following array and search string.

NSArray *values =[NSArray arrayWithObjects:@"abc",@"xyz",@"cba",@"yzx",nil];

NSString *search = @"startcba";

I want to search string's end part within an array elements. My expected search result will be @"cba". Please let me know how to find the desire value in array for giving search.

Thanks,

2
  • 1
    always the three last characters ? If so, get the substring and send [myArray indexOfObject:myString]. Commented Jul 22, 2011 at 12:06
  • Sorry, it can be of any length, like : NSArray *values =[NSArray arrayWithObjects:@"abc",@"xyz",@"cba",@"yzx",@"Abcd",nil]; NSString *search = @"startabcd"; Commented Jul 23, 2011 at 6:17

2 Answers 2

4

You can use NSPredicate to get the elements that satisfy your requirement.

NSPredicate * predicate = [NSPredicate predicateWithFormat:@" %@ ENDSWITH SELF ", search];
NSArray * searchResults = [values filteredArrayUsingPredicate:predicate];
Sign up to request clarification or add additional context in comments.

2 Comments

You can specify c and d in the predicate for case and diacritic insensitivity. So, predicate format looks like this @" %@ ENDSWITH[cd] SELF "
Thanks Deepak and EmptyStack for providing easy and exact solution.
1

The NSPredicates way is great.

Here is an approach with rangeOfString:

NSArray *values =[NSArray arrayWithObjects:@"abc",@"xyz",@"cba",@"yzx",nil];

NSString *search = @"startcba";
NSUInteger searchLength = [search length];
NSString *result = nil;

for (NSString *val in values)
{
    NSUInteger valLength = [val length];
    NSRange expectedRange = NSMakeRange(searchLength - valLength, valLength);
    NSRange rng = [search rangeOfString:val];

    if ( rng.location == expectedRange.location && rng.length == expectedRange.length )
    {
        result = val;
        break;
    }
}

1 Comment

Thanks, for your rangeOfString approach is equally good like deepak's and it can also allow me to find the index of items in the same loop. Sorry, i have to accept deepak's answer as it is exactly what i needed. I appreciate your valuable help.

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.