How to remove the last character from Stringbuilder

Posted by hmloo on Geeks with Blogs See other posts from Geeks with Blogs or by hmloo
Published on Sun, 08 Apr 2012 23:12:27 GMT Indexed on 2012/04/09 5:31 UTC
Read the original article Hit count: 235

Filed under:

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);
    }
}

© Geeks with Blogs or respective owner