0

我做了一个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];
4

1 回答 1

1

这似乎是因为您使用第一行从原始字符串设置了字符串的容量。

NSMutableString *html = [NSMutableString stringWithCapacity:[str length]];

I believe this sets a minimum capacity size and while it can grow beyond this freely it cannot shrink to your new size.

A quick fix would probably be to set the length initially to 1 or something smaller than the smallest expected text.

Example:

NSMutableString *html = [NSMutableString stringWithCapacity:1];

You could simply use:

NSMutableString *html = [[NSMutableString alloc] init];

I tried with this code and it works exactly like it should

NSMutableString *html = [[NSMutableString alloc] init];
NSLog(@"Before: %u", [html length]);

NSScanner *scanner = [NSScanner scannerWithString:@"<a>this is a test</a>"];
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;
}

NSLog(@"After: %u", [html length]);
于 2013-04-07T22:30:08.647 回答