-1

I have:

String test = "Hello,";
String test2 = "Hello";

I want to replace the last character if it is a comma with an empty string. I currently have:

String var = test.Remove(str.Length - 1, 1) + "";
String var = test2.Remove(str.Length - 1, 1) + "";

That would always replace the last character, even if it was not a comma.

Lance U. Matthews
  • 15,725
  • 6
  • 48
  • 68
David
  • 25
  • 5
  • What if the string ends with multiple consecutive commas? Should they all be removed, or only the last character? – Lance U. Matthews Nov 15 '19 at 00:48
  • 1
    Does this answer your question? [Remove last specific character in a string c#](https://stackoverflow.com/questions/20246461/remove-last-specific-character-in-a-string-c-sharp) or [Trim last character from a string](https://stackoverflow.com/q/20246461/150605) – Lance U. Matthews Nov 15 '19 at 00:50

1 Answers1

4

You can use .TrimEnd like so:

String test = "Hello,";
test = test.TrimEnd(',');
Loocid
  • 6,112
  • 1
  • 24
  • 42