我正在尝试减少 NSString 的长度而不用这种方法拆分最后一个单词:
// cut a string by words
- (NSString* )stringCutByWords:(NSString *)string toLength:(int)length;
{
// search backwards in the string for the beginning of the last word
while ([string characterAtIndex:length] != ' ' && length > 0) {
length--;
}
// if the last word was the first word of the string search for the end of the word
if (length <= 0){
while ([string characterAtIndex:length] != ' ' && length > string.length-1) {
length++;
}
}
// define the range you're interested in
NSRange stringRange = {0, length};
// adjust the range to include dependent chars
stringRange = [string rangeOfComposedCharacterSequencesForRange:stringRange];
// Now you can create the short string
string = [string substringWithRange:stringRange];
return [NSString stringWithFormat:@"%@...",string];
}
现在我的问题是:objective-c 或 cocoa-touch 中是否有我没有看到的内置方式,或者是否有“更好”的方式来做到这一点,因为我对这个解决方案不太满意。
问候和感谢 C4rmel 的帮助