Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C#
Tip/Trick

Using StringBuilder Length Property

Rate me:
Please Sign up or sign in to vote.
3.82/5 (5 votes)
4 May 2017CPOL 17.5K   14
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:

C#
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:

C#
sb.length -= 2;
result = sb.ToString ( );

or, more elegantly:

C#
sb.length -= ", ".Length;
result = sb.ToString ( );

If one wants, the following could be used:

C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
In 1964, I was in the US Coast Guard when I wrote my first program. It was written in RPG (note no suffixing numbers). Programs and data were entered using punched cards. Turnaround was about 3 hours. So much for the "good old days!"

In 1970, when assigned to Washington DC, I started my MS in Mechanical Engineering. I specialized in Transportation. Untold hours in statistical theory and practice were required, forcing me to use the university computer and learn the FORTRAN language, still using punched cards!

In 1973, I was employed by the Norfolk VA Police Department as a crime analyst for the High Intensity Target program. There, I was still using punched cards!

In 1973, I joined Computer Sciences Corporation (CSC). There, for the first time, I was introduced to a terminal with the ability to edit, compile, link, and test my programs on-line. CSC also gave me the opportunity to discuss technical issues with some of the brightest minds I've encountered during my career.

In 1975, I moved to San Diego to head up an IR&D project, BIODAB. I returned to school (UCSD) and took up Software Engineering at the graduate level. After BIODAB, I headed up a team that fixed a stalled project. I then headed up one of the two most satisfying projects of my career, the Automated Flight Operations Center at Ft. Irwin, CA.

I left Anteon Corporation (the successor to CSC on a major contract) and moved to Pensacola, FL. For a small company I built their firewall, given free to the company's customers. An opportunity to build an air traffic controller trainer arose. This was the other most satisfying project of my career.

Today, I consider myself capable.

Comments and Discussions

 
QuestionDifficult to follow Pin
Imagiv13-May-17 9:18
Imagiv13-May-17 9:18 
GeneralOr Pin
PIEBALDconsult5-May-17 4:50
mvePIEBALDconsult5-May-17 4:50 
GeneralRe: Or Pin
gggustafson7-May-17 10:37
mvagggustafson7-May-17 10:37 
GeneralRe: Or Pin
PIEBALDconsult7-May-17 14:11
mvePIEBALDconsult7-May-17 14:11 
GeneralRe: Or Pin
gggustafson7-May-17 18:46
mvagggustafson7-May-17 18:46 
GeneralRe: Or Pin
PIEBALDconsult8-May-17 3:41
mvePIEBALDconsult8-May-17 3:41 
GeneralRe: Or Pin
gggustafson8-May-17 5:38
mvagggustafson8-May-17 5:38 
QuestionNot so good example Pin
Klaus Luedenscheidt4-May-17 18:30
Klaus Luedenscheidt4-May-17 18:30 
AnswerRe: Not so good example Pin
gggustafson7-May-17 10:39
mvagggustafson7-May-17 10:39 
SuggestionReinvent the wheel Pin
Pakosh4-May-17 10:58
Pakosh4-May-17 10:58 
GeneralRe: Reinvent the wheel Pin
George Swan4-May-17 21:05
mveGeorge Swan4-May-17 21:05 
GeneralRe: Reinvent the wheel Pin
gggustafson7-May-17 10:40
mvagggustafson7-May-17 10:40 
Please see my response to Klaus Luedenscheidt.

Thanks for your comment.
Gus Gustafson

SuggestionWhy not Pin
Member 24433064-May-17 9:37
Member 24433064-May-17 9:37 
GeneralRe: Why not Pin
gggustafson7-May-17 10:46
mvagggustafson7-May-17 10:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.