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("\">")
.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.