我正在从字符串中删除文本以及用空行替换每行的内容.
一些背景: 我正在编写一个比较两个字符串的比较函数.它的工作正常,并在两个单独的Web浏览器中显示.当我尝试向下滚动我的浏览器时,字符串是不同的长度,我想用空行替换我删除的文本,以便我的字符串长度相同.
在下面的代码中,我想要计算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();
}
Run Code Online (Sandbox Code Playgroud)
pon*_*cha 69
int numLines = aDiff.text.Length - aDiff.text.Replace(Environment.NewLine, string.Empty).Length;
int numLines = aDiff.text.Split('\n').Length;
两者都会给你文字中的行数......
Crn*_*ena 12
您还可以使用 Linq 来计算行的出现次数,如下所示:
int numLines = aDiff.Count(c => c.Equals('\n')) + 1;
Run Code Online (Sandbox Code Playgroud)
晚了,但提供了其他答案的替代方案。
一种不会分配新字符串或字符串数组的变体
private static int CountLines(string str)
{
if (str == null)
throw new ArgumentNullException("str");
if (str == string.Empty)
return 0;
int index = -1;
int count = 0;
while (-1 != (index = str.IndexOf(Environment.NewLine, index + 1)))
count++;
return count + 1;
}
Run Code Online (Sandbox Code Playgroud)
小智 7
int newLineLen = Environment.NewLine.Length;
int numLines = aDiff.text.Length - aDiff.text.Replace(Environment.NewLine, string.Empty).Length;
if (newLineLen != 0)
{
numLines /= newLineLen;
numLines++;
}
Run Code Online (Sandbox Code Playgroud)
稍微更健壮,考虑到第一行不会有换行符。
效率不高,但仍然:
var newLineCount = aDiff.Text.Split('\n').Length -1;
Run Code Online (Sandbox Code Playgroud)
我对不同的方法(Split、Replace、for loop over chars、Linq.Count)进行了一系列性能测试,获胜者是 Replace 方法(当字符串小于 2KB 时,Split 方法稍微快一些,但不多)。
但是接受的答案中有 2 个错误。一个错误是当最后一行不以换行符结尾时,它不会计算最后一行。另一个错误是,如果您在 Windows 上读取带有 UNIX 行结尾的文件,则它不会计算任何行,因为 Environment.Newline\r\n
存在并且不会存在(您始终可以使用,\n
因为它是行结尾的最后一个字符) UNIX 和 Windows)。
所以这里有一个简单的扩展方法......
public static int CountLines(this string text)
{
int count = 0;
if (!string.IsNullOrEmpty(text))
{
count = text.Length - text.Replace("\n", string.Empty).Length;
// if the last char of the string is not a newline, make sure to count that line too
if (text[text.Length - 1] != '\n')
{
++count;
}
}
return count;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
54651 次 |
最近记录: |