Ios 从NSAttribute字符串中提取最后50行
有没有一种简单的方法来拆分Ios 从NSAttribute字符串中提取最后50行,ios,split,nsmutableattributedstring,Ios,Split,Nsmutableattributedstring,有没有一种简单的方法来拆分NSAttributedString以便只得到最后50行左右的内容 NSMutableAttributedString *resultString = [receiveView.attributedText mutableCopy]; [resultString appendAttributedString:[ansiEscapeHelper attributedStringWithANSIEscapedString:message]]; if ([[resultStr
NSAttributedString
以便只得到最后50行左右的内容
NSMutableAttributedString *resultString = [receiveView.attributedText mutableCopy];
[resultString appendAttributedString:[ansiEscapeHelper attributedStringWithANSIEscapedString:message]];
if ([[resultString.string componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] count]>50) {
//resultString = [resultString getLastFiftyLines];
}
您可以使用AttributedString的子字符串方法:
if ([resultString length]>50) {
resultString = [resultString attributedSubstringFromRange:NSMakeRange(0, 50)];
}
NSMakeRange-0告诉我们从哪里开始,50是子字符串的长度
有没有一种简单的方法可以拆分NSAttributedString,这样我就只能得到最后50行左右的内容
NSMutableAttributedString *resultString = [receiveView.attributedText mutableCopy];
[resultString appendAttributedString:[ansiEscapeHelper attributedStringWithANSIEscapedString:message]];
if ([[resultString.string componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] count]>50) {
//resultString = [resultString getLastFiftyLines];
}
否。您必须请求字符串
并确定您感兴趣的范围,然后使用API(如-[NSAttributedString attributedSubstringFromRange:
)从源代码派生出一个新的NSAttributedString
表示:
- (NSAttributedString *)lastFiftyLinesOfAttributedString:(NSAttributedString *)pInput
{
NSString * string = pInput.string;
NSRange rangeOfInterest = ...determine the last 50 lines in "string"...;
return [pInput attributedSubstringFromRange:rangeOfInterest];
}
这是最后50个字符。我相信OP正在寻找最后50行。让我们再检查一下。因为他在问题中使用[resultString length]>50,这不是前50个字符吗?从0到50?这是50个字符,而不是行。
componentsSeparatedByCharactersInSet:
返回一个字符串数组,因此count
是数组中每个点到字符串的长度,所以是50行,而不是字符。您是在询问行还是字符?([resultString length]>50)-关于字符,而不是行,我想这两种方法都适用,但我更喜欢行。字符串中的行是根据字体大小+ui元素宽度+换行来标识的。如果50个字符适用于,请不要使其过于复杂,并像我的回答中那样使用子字符串。这是一个带有ansi编码和大量“\n”字符的属性字符串。因此,在这种情况下,您的行定义不正确。这意味着对Justins答案的一些修改可能对meSubstring更有效。如果您猜测文本末尾可能有75行,请使用componentsSeparatedBy…
拆分行,然后在生成的数组中取最后50行。如果不是50,请加倍猜测并重试。(一定要扔掉结果数组中的第一行,因为它可能是部分的。)这听起来不太难。。。我想我可以从以下内容确定最后50行:[[resultString.string ComponentsParatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]count]但如何使用该API从中生成NSRange…@davidkarsson,您可以将从-componentsSeparatedByCharactersInSet:
返回的最后50个字符串的-length
相加,并为每个换行添加1个字符串(由-componentsSeparatedByCharactersInSet:
省略)。总和是感兴趣字符串的长度(例如最后234个字符),因此NSRange
将是{string.length-sum/*location*/,sum/*length*/}
。