phil crowe
phil crowe

Reputation: 887

TrimEnd() not working

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?

Upvotes: 14

Views: 26023

Answers (6)

Henk Holterman
Henk Holterman

Reputation: 273229

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.

Upvotes: 29

L W
L W

Reputation: 41

The catch is that mystring.Trim(',') will only work if you reassign it to the string itself like this:

mystring = mystring.Trim(',')

Upvotes: 4

Yasin Sunmaz
Yasin Sunmaz

Reputation: 1

 if (model != null && ModelState.IsValid)
                {
                    var categoryCreate = new Categories
                    {
                        CategoryName = model.CategoryName.TrimStart().TrimEnd(),
                        Description = model.Description.TrimStart().TrimEnd()
                    };
                    _CategoriesService.Create(categoryCreate);
                }

TrimStart().TrimEnd() == Left Trim and Right Trim

Upvotes: -1

Rejish
Rejish

Reputation: 21

"value, ".Trim().TrimEnd(",") should also work.

Upvotes: 1

Daniel Pratt
Daniel Pratt

Reputation: 12077

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;
}

Upvotes: 10

Geert Immerzeel
Geert Immerzeel

Reputation: 564

Try this:

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

Works for me.

Upvotes: 5

Related Questions