我做了一个RSS阅读器,我正在解析描述,但是描述中有HTML标签,所以我用下面的方法创建了一个NSString的类别来清除标签:
- (NSString *)stripTags:(NSString *)str
{
NSMutableString *html = [NSMutableString stringWithCapacity:[str length]];
NSScanner *scanner = [NSScanner scannerWithString:str];
scanner.charactersToBeSkipped = NULL;
[scanner setCharactersToBeSkipped:nil];
NSString *tempText = nil;
while (![scanner isAtEnd])
{
[scanner scanUpToString:@"<" intoString:&tempText];
if (tempText != nil)
[html appendString:tempText];
[scanner scanUpToString:@">" intoString:NULL];
if (![scanner isAtEnd])
[scanner setScanLocation:[scanner scanLocation] + 1];
tempText = nil;
}
return html;
}
这在删除 HTML 标签时效果很好,这不是问题。问题是我将描述设置为最多 100 个字符的长度,但它仍在计算该字符数中已删除的 HTML 标记。所以有些描述根本不显示,或者有些描述很短。我需要知道如何删除 HTML 标签,这样它们就不会占用任何字符数。
如果你需要,这里是我设置我的描述:
NSString *dots;
int length = [self.description length];
if (length > 100)
{
length = 100;
dots = [NSString stringWithFormat:@"..."];
}
else
{
dots = [NSString stringWithFormat:@""];
}
NSString *description = [NSString stringWithFormat:@"%@%@", [self.description substringToIndex:length], dots];