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

时间:2012-06-25 12:23:50

标签: 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();
    }

11 个答案:

答案 0 :(得分:66)

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

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

  3. 两者都会在文本中给出行数......

答案 1 :(得分:6)

效率不高,但仍然:

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

答案 2 :(得分: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 :(得分:3)

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

略微更强大,占第一行不会有换行符。

答案 4 :(得分:3)

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

int numLines = aDiff.text.LineCount();

代码:

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

玩得开心......

答案 5 :(得分:3)

我做了一堆不同方法的性能测试(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;
}

答案 6 :(得分:2)

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

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

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

答案 7 :(得分:2)

高效且成本最低的内存。

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

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

ModelChoiceField

引用:µBioDieter Meemken

答案 8 :(得分:1)

public static int CalcStringLines(string text)
{
    int count = 1;
    for (int i = 0; i < text.Length; i++)
    {
        if (text[i] == '\n') count++;
    }

    return count;
}

这是最快/最简单/没有内存分配的方式...

答案 9 :(得分:0)

using System.Text.RegularExpressions;

Regex.Matches(text, "\n").Count

考虑速度和内存使用情况,我认为计算'\n'的出现是最有效的方法。

使用split('\n')是一个坏主意,因为它会创建新的字符串数组,因此其性能和效率很差!特别是当您的字符串变大并且包含更多行时。

用空字符替换'\n'字符并计算差值也不是很有效,因为它应该执行一些操作,例如搜索,创建新字符串和内存分配等。

您只能执行一项操作,即搜索。因此,您可以按照@lokimidgard的建议,计算字符串中'\n'字符的出现。

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

答案 10 :(得分:0)

在这里晚了聚会,但是我认为这可以处理所有行,甚至最后一行(至少在Windows上):

Regex.Matches(text, "$", RegexOptions.Multiline).Count;