I use WinForms c#.I have string value like below,
string Something = "1,5,12,34,";
I need to remove last comma in a string. So How can i delete it ?
Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.
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.
Removing the first and last character In the example above, we removed the first character of a string by changing the starting point of a string to index position 1, then we removed the last character by setting its value to \0 . In C \0 means the ending of a string.
Try string.TrimEnd()
:
Something = Something.TrimEnd(',');
King King's answer is of course correct, and Tim Schmelter's comment is also good suggestion in your case.
But if you really want to remove the last comma in a string, you should find the index of the last comma and remove it like this:
string s = "1,5,12,34,12345"; int index = s.LastIndexOf(','); Console.WriteLine(s.Remove(index, 1));
Output will be:
1,5,12,3412345
Here is a demonstration
.
It is unlikely that you want this way but I want to point it out. And remember, the String.Remove
method doesn't remove any characters in the original string, it returns new string.
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