Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why string.TrimEnd not removing only last character in string

Tags:

string

c#

trim

I have string as below

2,44,AAA,BBB,1,0,,,

So now i want to remove only last comma in above string. So i want output as

2,44,AAA,BBB,1,0,,

I decided to use TrimeEnd as below

str.ToString.TrimEnd(',')

But it removed all the commas after 0. So i get output as below

2,44,AAA,BBB,1,0

Why it removes all the 3 commas after 0? I just need to remove last character in string

like image 670
James Avatar asked Jul 06 '13 11:07

James


People also ask

How do I remove the last character of a string?

The easiest way is to use the built-in substring() method of the String class. In order to remove the last character of a given String, we have to use two parameters: 0 as the starting index, and the index of the penultimate character.

How can I remove last digit from a string in C#?

Remove method can be used to remove last characters from a string in C#. The String. Remove method in C# creates and returns a new string after removing a number of characters from an existing string.

How do you trim the last 3 characters of a string?

To remove the last three characters from the string you can use string. Substring(Int32, Int32) and give it the starting index 0 and end index three less than the string length. It will get the substring before last three characters.

How do you remove the first and last character of a string?

The idea is to use the deleteCharAt() method of StringBuilder class to remove first and the last character of a string. The deleteCharAt() method accepts a parameter as an index of the character you want to remove.


1 Answers

Why it removes all the 3 commas after 0?

Because that's what it's documented to do:

Return value:
The string that remains after all occurrences of the characters in the trimChars parameter are removed from the end of the current string.

If you only want the final character removed, you could use:

if (str.EndsWith(","))
{
    str = str.Substring(0, str.Length - 1);
}

Or equivalently:

if (str.EndsWith(","))
{
    str = str.Remove(str.Length - 1);
}
like image 60
Jon Skeet Avatar answered Nov 03 '22 09:11

Jon Skeet