从NSString中删除所有出现的内容

时间:2014-02-09 06:11:17

标签: ios objective-c nsstring

我有一个HTML格式的NSSTring,我需要删除所有打开和关闭的strong代码

如何通过字符串删除所有<strong></strong>

3 个答案:

答案 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;
}