TrimEnd() not working

This should work:

string s = "Bar, ";

if (s.EndsWith(", "))
    s = s.Substring(0, s.Length - 2);

EDIT

Come to think of it, this would make a nice extension method:

public static String RemoveSuffix(this string value, string suffix)
{
    if (value.EndsWith(suffix))
        return value.Substring(0, value.Length - suffix.Length);

    return value;
}

Try this:

string someText = "some text, ";
char[] charsToTrim = { ',', ' ' };
someText = someText.TrimEnd(charsToTrim);

Works for me.


string txt = " testing, ,  ";
txt = txt.TrimEnd(',',' ');   // txt = "testing"

This uses the overload TrimEnd(params char[] trimChars). You can specify 1 or more chars that will form the set of chars to remove. In this case comma and space.

Tags:

C#

Asp.Net