I have a StringBuilder
instance where I am doing numerous sb.AppendLine("test");
for example.
How do I work out how many lines I have?
I see the class has .Length
but that tells me how many characters in all.
Any ideas?
I have a StringBuilder
instance where I am doing numerous sb.AppendLine("test");
for example.
How do I work out how many lines I have?
I see the class has .Length
but that tells me how many characters in all.
Any ideas?
You should be able to search for the number of occurences of \n in the string.
UPDATE: One way could be to split on the newline character and count the number of elements in the array as follows:
sb.ToString().Split('\n').length;
You could wrap StringBuilder
with your own class that would keep a count of lines as they are added or could the number of '\n' after your builder is full.
Regex.Match(builder.ToString(), Environment.NewLine).Length
Do a regex to count the number of line terminators (ex: \r\n) in the string. Or, load the strings into a text box and do a line count but thats the hack-ey way of doing it
Try this:
sb.ToString().Split(System.Environment.NewLine.ToCharArray()).Length;
You can split string bulider data into String[] array and then use String[].Length for number of lines.
something like as below:
String[] linestext = sb.Split(newline)
Console.Writeline(linetext.Length)
Derive your own line counting StringBuilder
where AppendLine
ups an internal line count and provides a method to get the value of line count.
You can create a wrapper class do the following:
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;
}
}
Sorted by efficiency:
The last one is extraordinary expensive and generates lots of garbage, don't use.
If you're going to use String.Split(), you will need to split the string with some options. Like this:
static void Main(string[] args)
{
var sb = new StringBuilder();
sb.AppendLine("this");
sb.AppendLine("is");
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();
}
This results in:
Number of lines: 4