This question can be rephrased as "how can I get a substring starting at the 4th word in a string?", which is slightly easier to solve. I'm also assuming here that strings with fewer than 4 words should become empty.
Anyway, the workhorse here is -enumerateSubstringsInRange:options:usingBlock:
, which we can use to find the 4th word.
NSString *substringFromFourthWord(NSString *input) {
__block NSUInteger index = NSNotFound;
__block NSUInteger count = 0;
[input enumerateSubstringsInRange:NSMakeRange(0, [input length]) options:(NSStringEnumerationByWords|NSStringEnumerationSubstringNotRequired) usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
if (++count == 4) {
// found the 4th word
index = substringRange.location;
*stop = YES;
}
}];
if (index == NSNotFound) {
return @"";
} else {
return [input substringFromIndex:index];
}
}
The way this works is we're asking -enumerateSubstrings...
to enumerate by words. When we find the 4th word, we save off its starting location and exit the loop. Now that we have the start of the 4th word we can just get the substring from that index. If we didn't get 4 words, we return @""
.