开发者

How to retrieve a StringBuilder Line Count?

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开发者_如何学Python me how many characters in all.

Any ideas?


Sorted by efficiency:

  1. Counting your AppendLine() calls
  2. Calling IndexOf() in a loop
  3. Using Regex
  4. Using String.Split()

The last one is extraordinary expensive and generates lots of garbage, don't use.


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.Matches(builder.ToString(), Environment.NewLine).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;
    }
}


Try this:

sb.ToString().Split(System.Environment.NewLine.ToCharArray()).Length;


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;


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("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();
}

This results in:

Number of lines: 5


UPDATE What Gabe said

b.ToString().Count(c => c =='\n') would work here too, and might not be much less efficient (aside from creating a separate copy of the string!).


A better way, faster than creating a string from the StringBuilder and splitting it (or creating the string and regexing it), is to look into the StringBuilder and count the number of '\n' characters there in.

The following extension method will enumerate through the characters in the string builder, you can then linq on it until to your heart is content.

    public static IEnumerable<char> GetEnumerator(this StringBuilder sb)
    {
        for (int i = 0; i < sb.Length; i++)
            yield return sb[i];
    }

... used here, count will be 4

        StringBuilder b = new StringBuilder();
        b.AppendLine("Hello\n");
        b.AppendLine("World\n");

        int lineCount = b.GetEnumerator().Count(c => c =='\n');


Derive your own line counting StringBuilder where AppendLine ups an internal line count and provides a method to get the value of line count.


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


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜