Delete last char of string

2019-01-12 17:04发布

I am retrieving a lot of informations in a list, linked to a database.

I want to create a string of groups, for someone who is connected to the website.

I use this to test ... But this is not dynamic so it is really bad:

string strgroupids = "6";

I want to use this now. But the string returned is something like 1,2,3,4,5,

groupIds.ForEach((g) =>
{
    strgroupids = strgroupids  + g.ToString() + ",";
    strgroupids.TrimEnd(',');
});

strgroupids.TrimEnd(new char[] { ',' });

I want to delete the , after the 5 but it's definitely not working.. Can someone help me?

标签: c# string char
9条回答
闹够了就滚
2楼-- · 2019-01-12 17:47

Add an extension method.

public static string RemoveLast(this string text, string character)
{
    if(text.Length < 1) return text;
    return text.Remove(text.ToString().LastIndexOf(character), character.Length);
}

then use:

yourString.RemoveLast(",");
查看更多
smile是对你的礼貌
3楼-- · 2019-01-12 17:49

As an alternate to adding a comma for each item you could just using String.Join:

var strgroupids = String.Join(",",  groupIds);

This will add the seperator ("," in this instance) between each element in the array.

查看更多
Viruses.
4楼-- · 2019-01-12 17:52

What about doing it this way

strgroupids = string.Join( ",", groupIds );

A lot cleaner.

It will append all elements inside groupIds with a ',' between each, but it will not put a ',' at the end.

查看更多
登录 后发表回答