C# 如何计算字符串中的行数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11189331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to count lines in a string?
提问by Pomster
I am removing text from a string and what to replace each line with a blank line.
我正在从字符串中删除文本以及用空行替换每一行的内容。
Some background:I am writing a compare function that compares two strings. Its all working fine and are displayed in there two separate web browsers. When i try scroll down on my browsers the strings are different lengths, I want to replace the text i am removeing with a blank line so that my strings are the same length.
一些背景:我正在编写一个比较两个字符串的比较函数。它一切正常,并显示在两个单独的 Web 浏览器中。当我尝试在浏览器上向下滚动时,字符串的长度不同,我想用空行替换我要删除的文本,以便我的字符串长度相同。
In the code below i am looking to count how many lines aDiff.Text has
在下面的代码中,我希望计算 aDiff.Text 有多少行
Here is my code:
这是我的代码:
public string diff_prettyHtmlShowInserts(List<Diff> diffs)
{
StringBuilder html = new StringBuilder();
foreach (Diff aDiff in diffs)
{
string text = aDiff.text.Replace("&", "&").Replace("<", "<")
.Replace(">", ">").Replace("\n", "<br>"); //¶
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();
}
采纳答案by poncha
int numLines = aDiff.text.Length - aDiff.text.Replace(Environment.NewLine, string.Empty).Length;int numLines = aDiff.text.Split('\n').Length;
int numLines = aDiff.text.Length - aDiff.text.Replace(Environment.NewLine, string.Empty).Length;int numLines = aDiff.text.Split('\n').Length;
both will give you number of lines in text...
两者都会给你文本中的行数......
回答by nunespascal
Inefficient, but still:
效率低下,但仍然:
var newLineCount = aDiff.Text.Split('\n').Length -1;
回答by Graham Bedford
int newLineLen = Environment.NewLine.Length;
int numLines = aDiff.text.Length - aDiff.text.Replace(Environment.NewLine, string.Empty).Length;
if (newLineLen != 0)
{
numLines /= newLineLen;
numLines++;
}
Slightly more robust, accounting for the first line that will not have a line break in it.
稍微更健壮,占第一行不会有换行符。
回答by Dieter Meemken
to make things easy, i put the solution from ponchain a nice extention method, so you can use it simply like this:
为了让事情变得简单,我将poncha的解决方案放在一个很好的扩展方法中,所以你可以像这样简单地使用它:
int numLines = aDiff.text.LineCount();
The code:
编码:
/// <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;
}
}
Have fun...
玩得开心...
回答by JeremyWeir
I did a bunch of performance testing of different methods (Split, Replace, for loop over chars, Linq.Count) and the winner was the Replace method (Split method was slightly faster when strings were less than 2KB, but not much).
我对不同的方法(Split、Replace、for loop over chars、Linq.Count)进行了一系列性能测试,获胜者是 Replace 方法(当字符串小于 2KB 时,Split 方法稍微快一些,但不多)。
But there's 2 bugs in the accepted answer. One bug is when the last line doesn't end with a newline it won't count the last line. The other bug is if you're reading a file with UNIX line endings on Windows it won't count any lines since Environment.Newline is \r\nand won't exist (you can always just use \nsince it's the last char of a line ending for UNIX and Windows).
但是接受的答案中有 2 个错误。一个错误是当最后一行不以换行符结尾时,它不会计算最后一行。另一个错误是,如果您在 Windows 上读取带有 UNIX 行结尾的文件,它不会计算任何行,因为 Environment.Newline\r\n存在并且不会存在(您总是可以使用,\n因为它是行结尾的最后一个字符) UNIX 和 Windows)。
So here's a simple extension method...
所以这里有一个简单的扩展方法......
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;
}
回答by lokimidgard
A variant that does not alocate new Strings or array of Strings
不分配新字符串或字符串数组的变体
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;
}
回答by CrnaStena
You can also use Linq to count occurrences of lines, like this:
您还可以使用 Linq 来计算行的出现次数,如下所示:
int numLines = aDiff.Count(c => c.Equals('\n')) + 1;
Late, but offers alternative to other answers.
晚了,但提供了其他答案的替代方案。
回答by Majid
using System.Text.RegularExpressions;
Regex.Matches(text, "\n").Count
I think counting the occurrence of '\n'is the most efficient way, considering speed and memory usage.
'\n'考虑到速度和内存使用情况,我认为计数发生是最有效的方法。
Using split('\n')is a bad idea because it makes new arrays of string so it's poor in performance and efficiency! specially when your string gets larger and contains more lines.
使用split('\n')是一个坏主意,因为它会生成新的字符串数组,因此性能和效率都很差!特别是当您的字符串变大并包含更多行时。
Replacing '\n'character with empty character and calculating the difference is not efficient too, because it should do several operations like searching, creating new strings and memory allocations etc.
'\n'用空字符替换字符并计算差值也不是很有效,因为它应该做一些操作,比如搜索、创建新字符串和内存分配等。
You can just do one operation, i.e. search. So you can just count the occurrence of '\n'character in the string, as @lokimidgard suggested.
您可以只执行一项操作,即search。所以你可以'\n'像@lokimidgard 建议的那样计算字符串中字符的出现次数。
It worth mentioning that searching for '\n'character is better than searching for "\r\n"(or Environment.NewLinein Windows), because the former (i.e. '\n') works for both Unix and Windows line endings.
值得一提的是,搜索'\n'字符比搜索"\r\n"(或Environment.NewLine在 Windows 中)更好,因为前者(即'\n')适用于 Unix 和 Windows 行尾。
回答by Radian Jheng
Efficient and cost least memory.
高效且成本最低的内存。
Regex.Matches( "Your String" , System.Environment.NewLine).Count ;
Off course, we can extend our string class
当然,我们可以扩展我们的字符串类
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 ;
}
}
reference : μBio, Dieter Meemken
回答by tmr6183
Late to the party here, but I think this handles all lines, even the last line (at least on windows):
晚到这里聚会,但我认为这可以处理所有行,甚至是最后一行(至少在 Windows 上):
Regex.Matches(text, "$", RegexOptions.Multiline).Count;

