Bonnie
Bonnie

Reputation: 219

Find words between 2 words?

Using Objective-C on my iPhone, is there a built-in method for NSString that finds a string appearing BETWEEN 2 other stings?

Search "my dog is my cat's best friend"... and return everything between "dog" and "best".

Or will I have to write my own? Any good ideas on where to start?

Thanks.

Upvotes: 1

Views: 170

Answers (2)

user121301
user121301

Reputation:

You can use substringWithRange:

    NSString *original = @"my dog is my cat's best friend";
    NSString *start = @"dog";
    NSString *end = @"best";
    NSRange startRange = [original rangeOfString:start];
    NSRange endRange = [original rangeOfString:end];
    NSRange range = NSMakeRange((startRange.location+[start length]), (endRange.location-startRange.location-[start length]));

    NSString *between = [original substringWithRange:range];

Upvotes: 4

Alex Reynolds
Alex Reynolds

Reputation: 96937

Perhaps take a look into using RegexKit.

Upvotes: 1

Related Questions