Search code examples
c#stringbuilder

Stringbuilder TrimEnd() why is it not removing my char?


Just a quick question.

I have a list collection = David, Bob, Ted

foreach (var value in collection)
{
    sb.Append(value);
    sb.Append(",");
}
sb.ToString().TrimEnd(',');

Output: David, Bob, Ted,

However when I try to trim off "," for the last value

sb.ToString().TrimEnd(',');

It still appears when I run it. Am I doing anything wrong?


Solution

  • Strings are immutable you are always creating a copy with a change and you are not using your new copy hens you do not see the change. To fix it use your copy of a string:

    var result = sb.ToString().TrimEnd(',');
    

    or modify string builder itself before calling ToString():

    sb.Length--;
    var result = sb.ToString();