[c#] Remove last specific character in a string c#

I use WinForms c#.I have string value like below,

string Something = "1,5,12,34,";

I need to remove last comma in a string. So How can i delete it ?

This question is related to c# trim

The answer is


Try below

Something..TrimEnd(",".ToCharArray());


The TrimEnd method takes an input character array and not a string. The code below from Dot Net Perls, shows a more efficient example of how to perform the same functionality as TrimEnd.

static string TrimTrailingChars(string value)
{
    int removeLength = 0;
    for (int i = value.Length - 1; i >= 0; i--)
    {
        char let = value[i];
        if (let == '?' || let == '!' || let == '.')
        {
            removeLength++;
        }
        else
        {
            break;
        }
    }
    if (removeLength > 0)
    {
        return value.Substring(0, value.Length - removeLength);
    }
    return value;
}

Or you can convert it into Char Array first by:

string Something = "1,5,12,34,";
char[] SomeGoodThing=Something.ToCharArray[];

Now you have each character indexed:

SomeGoodThing[0] -> '1'
SomeGoodThing[1] -> ','

Play around it


Try string.Remove();

string str = "1,5,12,34,";
string removecomma = str.Remove(str.Length-1);
MessageBox.Show(removecomma);

King King's answer is of course right. Also Tim Schmelter's comment is also good suggestion in your case.

But if you want really remove last comma in a string, you should find the index of last comma and remove like;

string s = "1,5,12,34,12345";
int index = s.LastIndexOf(',');
Console.WriteLine(s.Remove(index, 1));

Output will be;

1,5,12,3412345

Here a demonstration.

It is too unlikely you want this way but I want to point it. And remember, String.Remove method doesn't remove any character in original string, it returns new string.


When you have spaces at the end. you can use beliow.

ProcessStr = ProcessStr.Replace(" ", "");
Emails     = ProcessStr.TrimEnd(';');

Dim psValue As String = "1,5,12,34,123,12"
psValue = psValue.Substring(0, psValue.LastIndexOf(","))

output:

1,5,12,34,123