Geeks With Blogs
hmloo's World of .NET

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);
    }
}
Posted on Sunday, April 8, 2012 12:12 PM | Back to top


Comments on this post: How to remove the last character from Stringbuilder

# re: How to remove the last character from Stringbuilder
Requesting Gravatar...
I discovered the Length-- trick years ago, and it's one of my favorites --- however, note that if list is empty, the length with be zero, and sb.Length-- will throw an exception. So, check the length before you do the subtract.
Left by James Curran on Apr 09, 2012 2:20 AM

# re: How to remove the last character from Stringbuilder
Requesting Gravatar...
Thanxs Very Much.

It Works at my Case.

Best Regards,
Rohini G
Left by Rohini on Jun 14, 2012 12:18 AM

Your comment:
 (will show your gravatar)


Copyright © hmloo | Powered by: GeeksWithBlogs.net | Join free