假设我有以下字符串:
Mary had a little lamb, she also had a little sheep.
我的目标是在句号前后提取每个单词had
。(在这种情况下a little sheep
)。
我试过这样:
- (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;
}
如:
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?