How to replace last character of the string using c#?

Elegant but not very efficient. Replaces any character at the end of str with a comma.

str = Regex.Replace(str, ".$", ",");

That's a limitation of working with string. You can use StringBuilder if you need to do a lot of changes like this. But it's not worth it for the simple task you need.

str = str.Substring(0, str.Length - 1) + ",";

C# .NET makes it almost too easy.

str = str.TrimEnd('_')

No.

In C# strings are immutable and thus you can not change the string "in-place". You must first remove a part of the string and then create a new string. In fact, this is also means your original code is wrong, since str.Remove(str.Length -1, 1); doesn't change str at all, it returns a new string! This should do:

str = str.Remove(str.Length -1, 1) + ",";

Tags:

C#