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

问题描述 投票:35回答:9

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

一些背景:我正在编写一个比较两个字符串的比较函数。它的工作正常,并在两个单独的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();
    }
c#
9个回答
66
投票
  1. int numLines = aDiff.text.Length - aDiff.text.Replace(Environment.NewLine, string.Empty).Length;
  2. int numLines = aDiff.text.Split('\n').Length;

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


6
投票

效率不高,但仍然:

var newLineCount = aDiff.Text.Split('\n').Length -1;

6
投票

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

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

3
投票

为了方便起见,我把qazxsw poi的解决方案放在一个很好的扩展方法中,所以你可以像这样简单地使用它:

poncha

代码:

int numLines = aDiff.text.LineCount();

玩得开心...


3
投票

我做了一堆不同方法的性能测试(Split,Replace,for loop over chars,Linq.Count),获胜者是Replace方法(当字符串小于2KB时,Split方法稍快,但不多)。

但是在接受的答案中有2个错误。一个错误是当最后一行没有以换行结束时,它不会计算最后一行。另一个错误是,如果你在Windows上读取UNIX行结尾的文件,它将不计算任何行,因为Environment.Newline是/// <summary> /// Extension class for strings. /// </summary> public static class StringExtensions { /// <summary> /// Get the nummer of lines in the string. /// </summary> /// <returns>Nummer of lines</returns> public static int LineCount(this string str) { return str.Split('\n').Length; } } 并且不存在(你总是可以使用\r\n,因为它是行的最后一个字符串结束UNIX和Windows)。

所以这是一个简单的扩展方法......

\n

3
投票
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;
}

稍微强一些,占第一行不会有换行符。


2
投票

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

int newLineLen = Environment.NewLine.Length;
int numLines = aDiff.text.Length - aDiff.text.Replace(Environment.NewLine, string.Empty).Length;
if (newLineLen != 0)
{
    numLines /= newLineLen;
    numLines++;
}

迟到,但提供其他答案的替代方案。


2
投票

高效且成本最低的记忆。

int numLines = aDiff.Count(c => c.Equals('\n')) + 1;

当然,我们可以扩展我们的字符串类

Regex.Matches( "Your String" , System.Environment.NewLine).Count ;

参考:using System.Text.RegularExpressions ; public static class StringExtensions { /// <summary> /// Get the nummer of lines in the string. /// </summary> /// <returns>Nummer of lines</returns> public static int LineCount(this string str) { return Regex.Matches( str , System.Environment.NewLine).Count ; } } µBio


0
投票
Dieter Meemken

考虑速度和内存使用情况,我认为计算using System.Text.RegularExpressions; Regex.Matches(text, "\n").Count 的出现是最有效的方法。

使用'\n'是一个坏主意,因为它会生成新的字符串数组,因此它的性能和效率都很差!特别是当你的字符串变大并包含更多行时。

用空字符替换split('\n')字符并计算差异也不高效,因为它应该执行几个操作,如搜索,创建新字符串和内存分配等。

你可以只进行一次操作,即搜索。因此,您可以计算字符串中'\n'字符的出现次数,如@lokimidgard建议的那样。

值得一提的是,搜索'\n'字符比搜索'\n'(或Windows中的"\r\n")更好,因为前者(即Environment.NewLine)适用于Unix和Windows行结尾。

© www.soinside.com 2019 - 2024. All rights reserved.