我正在从字符串中删除文本以及用空行替换每行的内容。
一些背景: 我正在编写一个比较两个字符串的比较函数。它一切正常,并显示在两个独立的网络浏览器中。当我尝试在浏览器上向下滚动时,字符串长度不同,我想用空行替换要删除的文本,以便我的字符串长度相同。
在下面的代码中,我希望计算 aDiff.Text 有多少行
这是我的代码:
public string diff_prettyHtmlShowInserts(List<Diff> diffs)
{
StringBuilder html = new StringBuilder();
foreach (Diff aDiff in diffs)
{
string text = aDiff.text.Replace("&", "&").Replace("<", "<")
.Replace(">", ">").Replace("\n", "<br>"); //¶
switch (aDiff.operation)
{
case Operation.DELETE:
//foreach('\n' in aDiff.text)
// {
// html.Append("\n"); // Would like to replace each line with a blankline
// }
break;
case Operation.EQUAL:
html.Append("<span>").Append(text).Append("</span>");
break;
case Operation.INSERT:
html.Append("<ins style=\"background:#e6ffe6;\">").Append(text)
.Append("</ins>");
break;
}
}
return html.ToString();
}
最佳答案
方法一:
int numLines = aDiff.text.Length - aDiff.text.Replace _
(Environment.NewLine, string.Empty).Length;
方法二:
int numLines = aDiff.text.Split('\n').Length;
两者都会为您提供文本行数。
关于c# - 如何计算字符串中的行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11189331/