Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TrimEnd() not working

Tags:

c#

asp.net

I want to trim the end off a string if it ends in ", ". That's a comma and a space.

I've tried TrimEnd(', '), but this doesn't work. It has to be only if the string ends this way, so I can't just use .Remove to remove the last two characters. How can I do it?

like image 842
phil crowe Avatar asked Aug 19 '10 11:08

phil crowe


2 Answers

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.

like image 64
Henk Holterman Avatar answered Sep 23 '22 04:09

Henk Holterman


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;
}
like image 40
Daniel Pratt Avatar answered Sep 19 '22 04:09

Daniel Pratt