1

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
1
  • 1
    Look into NSString's rangeOfString function. Commented Feb 10, 2014 at 15:16

3 Answers 3

2

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");
}
Sign up to request clarification or add additional context in comments.

Comments

0

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!

Comments

0
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)];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.