Reputation: 5754
Suppose I have the following string:
Mary had a little lamb, she also had a little sheep.
My goal is to extract every word after had
and before the period. (In this case a little sheep
).
I tried this way:
- (NSInteger)indexOf:(NSString*)substring from:(NSInteger)starts {
NSRange r;
r.location = starts;
r.length = [self length] - r.location;
NSRange index = [self rangeOfString:substring options:NSLiteralSearch range:r];
if (index.location == NSNotFound) {
return -1;
}
return index.location + index.length;
}
As in:
NSInteger sheepSpot = [string indexOf:@"had" from:23];
// I know that I want to grab everything after the index of sheepSpot but before the period.
// Suppose now that I have an arbitrary number of periods in the sentence, how can I extract the above text without getting the wrong thing?
Upvotes: 0
Views: 187
Reputation: 46543
Try this one:
-(NSRange)lastRangeOf:(NSString *)substring inString:(NSString *)string{
return [string rangeOfString:substring options:NSBackwardsSearch];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{
NSString *string=@"had Mary had a little lamb, she also had a had little sheep.";
NSString *word=@"had";
NSRange hadRange=[self lastRangeOf:word inString:string];
NSInteger start=hadRange.location+word.length;
NSInteger lengthToCut=string.length-start;
NSString *substring=[string substringWithRange:NSMakeRange(start,lengthToCut)];
NSLog(@"->%@",substring);
}
Upvotes: 1
Reputation: 318804
This code will find the last "had" and the last period and give you everything in between:
NSString *text = @"Mary had a little lamb, she also had a little sheep.";
NSString *subtext = nil;
NSRange lastHadRange = [text rangeOfString:@"had" options:NSBackwardsSearch];
if (lastHadRange.location != NSNotFound) {
NSRange lastPeriodRange = [text rangeOfString:@"." options:NSBackwardsSearch];
if (lastPeriodRange.location != NSNotFound) {
NSUInteger start = lastHadRange.location + lastHadRange.length;
NSUInteger length = lastPeriodRange.location - start;
subtext = [text substringWithRange:NSMakeRange(start, length)];
}
}
NSLog(@"Subtext is: %@", subtext);
Upvotes: 1