Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove last specific character in a string c#

Tags:

c#

trim

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 ?

like image 456
user3042186 Avatar asked Nov 27 '13 15:11

user3042186


People also ask

How do I remove a specific character from a string?

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.

How do I remove the last 3 characters from 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 get rid of the first and last character in a string c?

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.


2 Answers

Try string.TrimEnd():

Something = Something.TrimEnd(','); 
like image 130
King King Avatar answered Sep 26 '22 11:09

King King


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.

like image 33
Soner Gönül Avatar answered Sep 22 '22 11:09

Soner Gönül