Search
Close this search box.

How to remove the last character from Stringbuilder

We usually use StringBuilder to append string in loops and make a string of each data separated by a delimiter. but you always end up with an extra delimiter at the end. This code sample shows how to remove the last delimiter from a StringBuilder.

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;

class Program
{
    static void Main()
    {
        var list =Enumerable.Range(0, 10).ToArray();
        StringBuilder sb = new StringBuilder();
        foreach(var item in list)
        {
            sb.Append(item).Append(",");
        }
        sb.Length--;//Just reduce the length of StringBuilder, it's so easy
        Console.WriteLine(sb);
    }
}

//Output : 0,1,2,3,4,5,6,7,8,9
Alternatively,  we can use string.Join for the same results, please refer to blow code sample.

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;

class Program
{
    static void Main()
    {
        var list = Enumerable.Range(0, 10).Select(n => n.ToString()).ToArray();
        string str = string.Join(",", list);
        Console.WriteLine(str);
    }
}
This article is part of the GWB Archives. Original Author: hmloo`s Worl of .NET

Related Posts