Using StringBuilder Length Property






3.82/5 (5 votes)
Using StringBuilder Length to eliminate unwanted trailing characters
Background
Often, when working with the StringBuilder [^], unwanted characters are added to the end to the string. This is usually encountered when converting a list of items into a string. For example:
using System;
using System.Text;
:
:
int [ ] items = new int [ ]
{
1,
2,
3,
4,
5
};
string result = String.Empty;
StringBuilder sb = new StringBuilder ( );
:
:
foreach ( int item in items )
{
sb.AppendFormat ( "{0}, ",
item );
}
result = sb.ToString ( );
Unfortunately, result contains trailing comma-space characters. To eliminate the unwanted characters, the programmer may use the String.LastIndexOf [^] and String.Remove [^] methods.
Solution
A simpler, but often overlooked, alternative is to use the StringBuilder Length property that "gets or sets the length of the current StringBuilder object." In the example, we can eliminate the unwanted trailing characters using:
sb.length -= 2;
result = sb.ToString ( );
or, more elegantly:
sb.length -= ", ".Length;
result = sb.ToString ( );
If one wants, the following could be used:
const string SB_FORMAT_SUFFIX = ", ";
:
:
foreach ( int item in items )
{
sb.AppendFormat ( "{0}{1}",
item,
SB_FORMAT_SUFFIX );
}
sb.length -= SB_FORMAT_SUFFIX.Length;
result = sb.ToString ( );
Using this simple method eliminates the hassles associated with LastIndexOf and Remove. I also believe that readability is increased.