1

我有一个 html 字符串,我想一次允许 1 个换行符。我正在尝试用“\n”替换所有“\n\n”。但最后我得到了双换行符。

是否可以打印字符串的内容以查看内容是什么,而不是在输出窗口中显示“\n”而不是换行。

while ((range = [html rangeOfString:@"\n\n"]).length) 
{
   [html replaceCharactersInRange:range withString:@"\n"];
}

编辑: html 已转换为纯文本(因此字符串中没有 BR 标签)

4

2 回答 2

4

如果你有不确定数量的换行要压缩成一个,你可以使用 NSRegularExpression。就像是:

NSRegularExpression *squeezeNewlines = [NSRegularExpression regularExpressionWithPattern:@"\n+" options:0 error:nil];
[squeezeNewlines replaceMatchesInString:html options:0 range:NSMakeRange(0, [html length]) withTemplate:@"\n"];

(写在我的浏览器中,没有测试,因为我手头没有最近的 Mac,所以如果我搞砸了,请告诉我。)

于 2011-11-21T19:10:54.723 回答
1

你为什么不改用:

- (NSUInteger)replaceOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)opts range:(NSRange)searchRange
于 2011-11-21T18:24:50.330 回答