如何计算字符串中的行数?

Pom*_*ter 38 c#

我正在从字符串中删除文本以及用空行替换每行的内容.

一些背景: 我正在编写一个比较两个字符串的比较函数.它的工作正常,并在两个单独的Web浏览器中显示.当我尝试向下滚动我的浏览器时,字符串是不同的长度,我想用空行替换我删除的文本,以便我的字符串长度相同.

在下面的代码中,我想要计算aDiff.Text有多少行

这是我的代码:

public string diff_prettyHtmlShowInserts(List<Diff> diffs)
    {
        StringBuilder html = new StringBuilder();

        foreach (Diff aDiff in diffs)
        {
            string text = aDiff.text.Replace("&", "&amp;").Replace("<", "&lt;")
              .Replace(">", "&gt;").Replace("\n", "<br>"); //&para;
            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

  1. int numLines = aDiff.text.Length - aDiff.text.Replace(Environment.NewLine, string.Empty).Length;

  2. int numLines = aDiff.text.Split('\n').Length;

两者都会给你文字中的行数......

  • 请注意,就性能而言,拆分字符串将分配空间以创建数组,以便它可以计算数组中元素的最终数量.这是非常低效的,如果你在足够大的输入文本上运行它,它实际上会生成OutOfMemoryExceptions.下面的@GrahamBedford [答案](http://stackoverflow.com/a/34903526/90852)是最正确的. (5认同)
  • 有一个问题。如果Environment.NewLine是\r\n,那么有2个字符长度,它将导致双新行。因此这将解决这个问题 int numLines = (aDiff.text.Length - aDiff.text.Replace _ (Environment. NewLine, string.Empty).Length) / Environment.NewLine.Length; (3认同)

Crn*_*ena 12

您还可以使用 Linq 来计算行的出现次数,如下所示:

int numLines = aDiff.Count(c => c.Equals('\n')) + 1;
Run Code Online (Sandbox Code Playgroud)

晚了,但提供了其他答案的替代方案。

  • 仅在此处回答不会创建新的不必要的对象 (4认同)

lok*_*ard 8

一种不会分配新字符串或字符串数​​组的变体

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)

稍微更健壮,考虑到第一行不会有换行符。


nun*_*cal 6

效率不高,但仍然:

var newLineCount = aDiff.Text.Split('\n').Length -1;
Run Code Online (Sandbox Code Playgroud)


Jer*_*eir 6

我对不同的方法(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)