简体   繁体   中英

Count line by searching crlf (0d0a)

I would like to count number of lines in a file based on crlf ( 0D0A ) count. My current code only counting the number of lines based on cr ( 0D ). Can anybody give suggestion?

public static int Countline(string file)
{
    var lineCount = 0;
    using (var reader = File.OpenText(file))
    {
        while (reader.ReadLine() != null)
        {
            lineCount++;
         }
    }
    return lineCount;
}

Usage:

Countline("text.txt", "\r\n");

Method:

public static int Countline(string file, string lineSeperator)
{
    string text = File.ReadAllText(file);

    return System.Text.RegularExpressions.Regex.Matches(text, lineSeperator).Count;
}
string content = System.IO.File.ReadAllText( fileName );
int numMatches = content.Select((c, i) => content.Substring(i)).Count(sub => sub.StartsWith(Environment.NewLine));

Note I'm using Environment.NewLine for line endings but you can replace with the whole string if you prefer.

public int CountLines(string Text)
{
    int count = 0;
    foreach (ReadOnlySpan<char> _ in Text.AsSpan().EnumerateLines())
    {
        count++;
    }

    return count;
}

Benchmark

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM