This will do it:
- (NSString *)getSnippetContaining:(NSString *)keyword
inString:(NSString *)theString
numberOfWords:(NSUInteger)wordCount
{
NSRange range = [theString rangeOfString:keyword
options:NSBackwardsSearch
range:NSMakeRange(0, theString.length)];
if (range.location == NSNotFound) {
return nil;
}
NSString *substring = [theString substringFromIndex:range.location];
NSArray *words = [substring componentsSeparatedByString:@" "];
if (wordCount > words.count) {
wordCount = words.count;
}
NSArray *snippetWords = [words subarrayWithRange:NSMakeRange(0, wordCount)];
NSString *snippet = [snippetWords componentsJoinedByString:@" "];
return snippet;
}
numberOfWords
is the length of the snippet you wish to extract from the input.