基於Insane-36的回答,我已經做到了。
- (NSString *)trimString:(NSString *)string aroundWord:(NSString *)word withRadius:(NSUInteger)radius {
NSString *prev = @"...", *next = @"...";
NSUInteger centerStr = [string rangeOfString:word].location + word.length/2;
NSUInteger start = centerStr - radius;
NSRange range = NSMakeRange(start, radius * 2);
if (range.location + range.length > string.length) {
range = NSMakeRange(string.length - range.length, range.length);
next = @"";
}
if ((int)(range.location - range.length/2) < 0) {
range = NSMakeRange(0, range.length);
prev = @"";
}
NSString *stringaRestituita = [string substringWithRange:range];
return [NSString stringWithFormat: @"%@%@%@", prev, stringaRestituita, next];
}
它對我來說非常合適。
您可能會考慮使用省略號字符而不是三個句號。 – bbarnhart