ear-fung.us I’m a programmer. I’m also pro-grammar.

3Jul/087

My First Objective-C Cocoa Code – “String Between”

I needed a string searching method in Objective-C for a little app I'm writing that searched a string and found substrings in-between two other strings... sort of a poor man's regex. It extends the NSString object so once you've imported it in your main header, you can call the method on an NSString object. I couldn't find anything in the Cocoa API that did what I was looking for so I did it myself.

Here's what I came up with... I present to you: "StringBetween"

StringBetween.h

@interface NSString (StringBetween)

-(NSString *)stringBetween:(NSString*)aString and:(NSString *)bString;

@end

StringBetween.m

#import "StringBetween.h"
@implementation NSString (StringBetween)

-(NSString *)stringBetween:(NSString *)aString and:(NSString *)bString
{
    NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];

    //Find the range of the first string
    NSRange aRange = [self rangeOfString:aString options:(NSCaseInsensitiveSearch)];

    if(aRange.length > 0){
        //Make a new range to search for the next string
        NSRange searchRange;
        searchRange.location = aRange.location;
        searchRange.length = [self length] - aRange.location;

        //Find the next string
        NSRange bRange = [self rangeOfString:bString options:(NSCaseInsensitiveSearch) range:searchRange];

        //NSLog(@"%d, %d", aRange.location, aRange.length);
        //NSLog(@"%d, %d", bRange.location, bRange.length);

        if(bRange.length > 0)
        {
            searchRange.location = aRange.location + aRange.length;
            searchRange.length = bRange.location - searchRange.location;

           return [self substringWithRange:searchRange];
        }
    }
    return @"";
    [autoreleasepool release];
}
@end

Here is an actual implementation example:

main.m

#import <cocoa/Cocoa.h>
#import "StringBetween.h"

int main (int argc, const char * argv[]) {

    NSString *thisString = @"The quick brown fox jumped over the lazy dog.";

    NSLog([thisString stringBetween:@"qui" and:@"the"]);
    //Returns @"ck brown fox jumped over "

    NSLog([thisString stringBetween:@"garbage" and:@"more garbage"]);
    //Returns @""

    return 0;
}

I hope I didn't muck up that code too bad. I'm still learning Objective-C.

Here's an X-Code project download if you want to see it in action.
Download this xcode project