NSString字符串过滤-NSScanner

    以HTML标签为例:

第一种方式:

- (NSString *)removeHTML:(NSString *)html {

    NSScanner *theScanner;

    NSString *text = nil;    

    theScanner = [NSScanner scannerWithString:html];    

    while ([theScanner isAtEnd] == NO) {

        // find start of tag

        [theScanner scanUpToString:@"<" intoString:NULL] ;

        // find end of tag

        [theScanner scanUpToString:@">" intoString:&text] ;        

        // replace the found tag with a space

        //(you can filter multi-spaces out later if you wish)

        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>", text]withString:@" "];

    }

    return html;

}


第二种方式,用NSString自带的Seprated自截断方法

- (NSString *)removeHTML2:(NSString *)html{

    NSArray *components = [html componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];

    

    NSMutableArray *componentsToKeep = [NSMutableArray array];

    for (int i = 0; i < [components count]; i = i + 2) {

        [componentsToKeep addObject:[components objectAtIndex:i]];

    }

    

    NSString *plainText = [componentsToKeep componentsJoinedByString:@""];

    return plainText;

}


原文:http://my.oschina.net/openlab/blog/155218


你可能感兴趣的:(过滤,NSScanner)