Luda
Luda

Reputation: 7068

NSString substring between predefined strings

How can I get a substring between predefined strings. For example:

NSString* sentence = @"Here is my sentence. I am looking for {start}this{end} word";
NSString* start = @"{start}";
NSString* end = @"{end}";
NSString* myWord = [do some stuff with:sentence and:start and:end];

NSLog(@"myWord - %@",myWord);

Log: myWord - this

Upvotes: 1

Views: 225

Answers (3)

ChikabuZ
ChikabuZ

Reputation: 10185

NSRange startRange = [sentence rangeOfString:start];
NSRange endRange = [sentence rangeOfString:end];

int startLocation = startRange.location + startRange.length;
int lenght = endRange.location - startLocation;

NSString* myWord = [sentence substringWithRange:NSMakeRange(startLocation, lenght)];

Upvotes: 0

Volker
Volker

Reputation: 4660

You can use rangeOfString:to get the location of each of the markers. Then use subStringWithRange:to extract the string part you want.

NSRange startRange = [sentence rangeOfString:start];
NSRange endRange = [sentence end];
NSString myWord = [NSString subStringWithRange:NSMakeRange(startRange.location+startRange.length, endRange.location-startRange.location+startRange.length)];

All code typed in Safari and no error handling included!

Upvotes: 0

Gavin
Gavin

Reputation: 8200

The following will give you the output you want:

NSString* sentence = @"Here is my sentence. I am looking for {start}this{end} word";
NSString* start = @"{start}";
NSString* end = @"{end}";

NSRange startRange = [sentence rangeOfString:start];
NSRange endRange = [sentence rangeOfString:end];

if (startRange.location != NSNotFound && endRange.location != NSNotFound) {
    NSString *myWord = [sentence substringWithRange:NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length)];
    NSLog(@"myWord - %@", myWord);
}
else {
    NSLog(@"myWord not found");
}

Upvotes: 2

Related Questions