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
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.
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.
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.
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.
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 thetrimChars
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With