我有一个 StringBuilder
实例,我在里面做了很多类似 sb.AppendLine("test");
的操作。
如何计算我有多少行?
我看到这个类有 .Length
, 但那只告诉我所有字符的数量。
有什么想法吗?
我有一个 StringBuilder
实例,我在里面做了很多类似 sb.AppendLine("test");
的操作。
如何计算我有多少行?
我看到这个类有 .Length
, 但那只告诉我所有字符的数量。
有什么想法吗?
按效率排序:
最后一个非常昂贵且会生成大量垃圾,请勿使用。
Environment.NewLine
、\r\n
、\n
,甚至是传递给其他方法的内容。 - Matthew Whited你可以使用自己的类将StringBuilder
进行包装,以便在添加行时保持计数或者在builder满后统计 '\n' 的数量。
Regex.Matches(builder.ToString(), Environment.NewLine).Count
public class Wrapper
{
private StringBuilder strBuild = null;
private int count = 0;
public Wrapper(){
strBuild = new StringBuilder();
}
public void AppendLine(String toAppendParam){
strBuild.AppendLine(toAppendParam);
count++;
}
public StringBuilder getStringBuilder(){
return strBuild;
}
public int getCount(){
return count;
}
}
试试这个:
sb.ToString().Split(System.Environment.NewLine.ToCharArray()).Length;
NewLine
字符串的长度)。 - Jeppe Stig Nielsen\r\n
。如果这个答案应该在所有机器上真正计算行数,只需删除.ToCharArray()
即可。 - Jack Miller更新 Gabe所说的话
b.ToString().Count(c => c =='\n') 这里也可以工作,而且效率可能不会比从 StringBuilder 创建一个单独的字符串并分割或创建字符串和正则表达式更低!
有一种更好的方法,比从 StringBuilder 创建字符串并分离它(或创建字符串并使用正则表达式)更快,即查看 StringBuilder 并计算其中的 '\n' 字符数。
下面这个扩展方法将枚举字符串生成器中的字符,您可以使用 Linq 对其进行操作。
public static IEnumerable<char> GetEnumerator(this StringBuilder sb)
{
for (int i = 0; i < sb.Length; i++)
yield return sb[i];
}
...在这里使用,计数将为4
StringBuilder b = new StringBuilder();
b.AppendLine("Hello\n");
b.AppendLine("World\n");
int lineCount = b.GetEnumerator().Count(c => c =='\n');
b.ToString().Count(c => c =='\n')
在这里也可以工作,并且可能不会比较低效(除了创建一个单独的字符串副本之外!)。 - Gabeb.ToString().Count(c => c =='\n')
的时间只需要我的枚举器的2/3。 - Binary Worrierstatic void Main(string[] args)
{
var sb = new StringBuilder();
sb.AppendLine("this");
sb.AppendLine("is");
sb.AppendLine("a");
sb.AppendLine("test");
// StringSplitOptions.None counts the last (blank) newline
// which the last AppendLine call creates
// if you don't want this, then replace with
// StringSplitOptions.RemoveEmptyEntries
var lines = sb.ToString().Split(
new string[] {
System.Environment.NewLine },
StringSplitOptions.None).Length;
Console.WriteLine("Number of lines: " + lines);
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
}
行数:5
您应该能够搜索字符串中 \n 的出现次数。
更新: 一种方法是在换行符上进行拆分,并按以下方式计算数组中的元素数量:
sb.ToString().Split('\n').length;
衍生自己的行计数 StringBuilder
,其中 AppendLine
增加内部行计数并提供获取行计数值的方法。
使用正则表达式来计算字符串中行终止符(例如:\r\n)的数量。或者,将字符串加载到文本框中并进行行计数,但这是一种不太优雅的方法。
String[] linestext = sb.Split(newline)
Console.Writeline(linetext.Length)