Finding Substrings in Objective-C

    • Tweet
    November 3rd, 2008 Posted by: josh - posted under:Snippets

    It’s times like this, that I miss ruby.

    I’m checking a url to see if it has a substring. It would be so easy if this was ruby:

    absolute_url.match(/my regex/).any?

    In Objective C, you have to use rangeOfString which returns a range. If I were to run this on the string “the quick brown fox” with an argument of “brown” it would return {10,14}. If it’s not found, it would return {NSNotFound, 0}. Let’s use that to check to see if the range was found. We’ll use NSMakeRange to create the NSNotFound range and NSEqualRanges to compare them:

    if(NSEqualRanges(NSMakeRange(NSNotFound, 0), [absoluteURL rangeOfString:@"my_substring"])){
    NSLog(@"my_substring not found in absoluteURL %@", absoluteURL);