TrimEnd() not working

2020-08-10 12:11发布

问题:

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?

回答1:

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.



回答2:

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


回答3:

Try this:

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

Works for me.



回答4:

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

mystring = mystring.Trim(',')


回答5:

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



回答6:

 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



标签: c# asp.net