开发者

how to match string portion with NSArray values in objective-c

开发者 https://www.devze.com 2023-03-22 18:35 出处:网络
I have following array and search string. NSArray *values =[NSArray arrayWithObjects:@\"abc\",@\"xyz\",@\"cba\",@\"yzx\",n开发者_如何转开发il];

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;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消