[英]Count line by searching crlf (0d0a)
I would like to count number of lines in a file based on crlf
( 0D0A
) count.我想根据
crlf
( 0D0A
)计数来计算文件中的行数。 My current code only counting the number of lines based on cr
( 0D
).我当前的代码仅根据
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. 注意我正在使用
Environment.NewLine
作为行尾,但是如果愿意,可以用整个字符串替换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.