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?
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.
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.
The catch is that mystring.Trim(',')
will only work if you reassign it to the string
itself like this:
mystring = mystring.Trim(',')
"value, ".Trim().TrimEnd(",")
should also work.
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
精彩评论