我有一个HTML格式的NSSTring,我需要删除所有打开和关闭的strong
代码
如何通过字符串删除所有<strong>
和</strong>
?
答案 0 :(得分:4)
尝试使用 stringByReplacingOccurrencesOfString:withString : NSString的方法
NSString *newString = nil;
NSString *resultString = nil;
newString = [htmlString stringByReplacingOccurrencesOfString:@"<strong>" withString:@""];
resultString = [newString stringByReplacingOccurrencesOfString:@"</strong>" withString:@""];
上面的代码假设要移除的html标记中没有空格, resultString 表示最终结果。
答案 1 :(得分:1)
使用stringByReplacingOccurrencesOfString替换字符串。
NSString *resultString = nil;
resultString = [[htmlString stringByReplacingOccurrencesOfString:@"<strong>" withString:@""] stringByReplacingOccurrencesOfString:@"</strong>" withString:@""];
或可以用作正则表达式
NSRange r;
NSString *s =@"Html String";
while ((r = [s rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
s = [s stringByReplacingCharactersInRange:r withString:@""];
return s;
答案 2 :(得分:0)
用扫描仪检查
-(NSString *)convertHTML:(NSString *)html {
NSScanner *myScanner;
NSString *text = nil;
myScanner = [NSScanner scannerWithString:html];
while ([myScanner isAtEnd] == NO) {
[myScanner scanUpToString:@"<" intoString:NULL] ;
[myScanner scanUpToString:@">" intoString:&text] ;
html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>", text] withString:@""];
}
//
html = [html stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
return html;
}