Search code examples
c#stringbuilder

Best way to remove the last character from a string built with stringbuilder


I have the following

data.AppendFormat("{0},",dataToAppend);

The problem with this is that I am using it in a loop and there will be a trailing comma. What is the best way to remove the trailing comma?

Do I have to change data to a string and then substring it?


Solution

  • The simplest and most efficient way is to perform this command:

    data.Length--;
    

    by doing this you move the pointer (i.e. last index) back one character but you don't change the mutability of the object. In fact, clearing a StringBuilder is best done with Length as well (but do actually use the Clear() method for clarity instead because that's what its implementation looks like):

    data.Length = 0;
    

    again, because it doesn't change the allocation table. Think of it like saying, I don't want to recognize these bytes anymore. Now, even when calling ToString(), it won't recognize anything past its Length, well, it can't. It's a mutable object that allocates more space than what you provide it, it's simply built this way.