I have following array and search string.
NSArray *values =[NSArray arrayWithObjects:@"abc",@"xyz",@"cba",@"yzx",n开发者_如何转开发il];
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,
You can use NSPredicate
to get the elements that satisfy your requirement.
NSPredicate * predicate = [NSPredicate predicateWithFormat:@" %@ ENDSWITH SELF ", search];
NSArray * searchResults = [values filteredArrayUsingPredicate:predicate];
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;
}
}
精彩评论