如何使用 Replace 方法仅将最后两个符号替换为无

How to replace only last two sign to nothing using method Replace

我有字符串 "55, 55,55, 55, ",我想仅使用方法 .Replace() 将最后两个字符(逗号和白色 space)替换为空。下面的示例清除了所有逗号,但我只想清除最后两个逗号。在 Java 你写:

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

如何正确编写才能仅使用 Replace 方法获得此效果?

使用Regex.Replace:

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

如果它总是两个字符,您还可以组合 String.EndsWithString.Substring,这可能比编译和应用正则表达式更便宜:

if (input.EndsWith(", ")) {
  input = input.Substring(0, input.Length - 2);
}