Jon
Jon

Reputation: 40032

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 me how many characters in all.

Any ideas?

Upvotes: 39

Views: 52006

Answers (10)

Jake Pearson
Jake Pearson

Reputation: 27717

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

Upvotes: 29

Binary Worrier
Binary Worrier

Reputation: 51711

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');

Upvotes: 2

code4life
code4life

Reputation: 15794

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

Upvotes: 2

swapneel
swapneel

Reputation: 3061

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)

Upvotes: 0

Koekiebox
Koekiebox

Reputation: 5963

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;
    }
}

Upvotes: 6

Hans Passant
Hans Passant

Reputation: 941317

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.

Upvotes: 34

John Warlow
John Warlow

Reputation: 2992

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

Upvotes: 1

Bravax
Bravax

Reputation: 10483

Try this:

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

Upvotes: 3

Ayubinator
Ayubinator

Reputation: 148

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

Upvotes: 0

Paul Hadfield
Paul Hadfield

Reputation: 6136

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;

Upvotes: 2

Related Questions