I have a long NSString e.g. "For performance reasons, a table view data source generally reuses UITableViewCell objects. The table view maintains a queue of cell objects that are marked for reuse. For example, if you were displaying a list that contained a 1000 rows it would be highly inefficient to create 1000 table view cells, whereas a lot of more effective to create the few currently in view."

Now if user search for word "maintains" then above NSString definitely have this word.. now i just want to show only rand of line with this word, not whole text. So the use will know that this text have this word and where it is.

-User search for "maintains". -code process the NSString. -Output will look like this.. "table view maintains a queue of cell objects that..." or this can be also a result.. "maintains a queue of cell objects that..." 2nd result would be great...

NSRange range = [myString rangeOfString:@"maintains" options:NSBackwardsSearch range:NSMakeRange(0, 11)];

NSLog(@"range.location: %lu", range.location);

NSString *substring = [myString substringFromIndex:range.location+1];

NSLog(@"substring: '%@'", substring);`

but no success...from this CODE

Please help me to get my target...

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top