// Articles. Tutorials. Utilities.
Home  |   Search  |   Login  
Categories Skip Navigation Links
New / All
Google / Android
Python / IronPython
SQL Server
Taking out the last comma in the list
When you make a list of items separated by commas, you will have that irritating comma at the end of list. This article discusses a couple of different ways of taking that comma (or the separator) out.
Table of Contents

A popular way of making a list of items separated by comma (or a space followed by comma) is to use a StringBuilder and as each item is appended, you would add that comma (or a space followed by a comma). For example, if you are getting list of tags from the database you will probably make a tag string where individual tags are separated by a comma and a space like the following:

while (reader.Read())
    tags.Append("<a href=\"").Append(href)
        .Append(reader["Tag"].ToString()).Append("</a>, ");

In the above code, you are cycling through a DataReader and making a list of tag links. In the last append a comma and a space are added. This works fine, that comma and space needs to be taken out for the last tag.

One way is to check whether that tag is the last tag and then not add it. But that approach does lot of unnecessary checking. Another way is to simply remove the last two characters after the entire string has been made.

// Take out the last comma and space
tags = tags.Remove(tags.Length - 2, 2);

In the above code, we use the Remove method that is available from StringBuilder. First parameter is the StartIndex and the second parameter is the number of characters to remove. So, here we are telling the StringBuilder to remove the last two characters.

The String class also has couple of Remove methods that work in similar way.

Bookmark and Share This

More Articles With Similar Tags
Top Tags in Related Articles
comma separated list
About  Contact  Privacy Policy  Site Map