-1

I've got string "55, 55,55, 55, " and I want to replace last two characters (comma and white space) to nothing using only the method .Replace(). The example below clear all commas but I want to clear only two last ones. In Java you write:

variable.replaceAll(", $","");  // it's correct effect two last characters are changed to nothing
Replace(", ","") // but in c# you get: 55555,5555 and Replace(", $","") doesn't work

How to write it properly to get this effect using only Replace method?

knittl
  • 246,190
  • 53
  • 318
  • 364
Medic2133
  • 21
  • 5
  • 2
    In C# we'd `TrimEnd(' ',',')` rather than busting out Regex for something as trivial as that... Could also `str[..^2]` if you know it's always 2 chars – Caius Jard Jan 04 '22 at 18:51

1 Answers1

0

Use Regex.Replace:

Regex.Replace(input, ", $", "");

If it is always two characters, you could also combine String.EndsWith and String.Substring, which is likely cheaper than compiling and applying a regex:

if (input.EndsWith(", ")) {
  input = input.Substring(0, input.Length - 2);
}
knittl
  • 246,190
  • 53
  • 318
  • 364