Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 708
Wesley Skeen Avatar asked Jun 20 '13 13:06

Wesley Skeen


People also ask

How do I remove a character from StringBuilder?

deleteCharAt() method removes the char at the specified position in this sequence. This sequence is shortened by one char.

How do I remove the last 3 characters from a string?

To remove the last three characters from the string you can use string. Substring(Int32, Int32) and give it the starting index 0 and end index three less than the string length. It will get the substring before last three characters.


1 Answers

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.

like image 78
Mike Perrenoud Avatar answered Oct 13 '22 14:10

Mike Perrenoud