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

后端 未结 1 792
予麋鹿
予麋鹿 2021-02-11 16:22
string str = \"Student_123_\";

I need to replace the last character \"_\" with \",\". I did it like this.

str.Remove(str.Length -1, 1)         


        
1条回答
  •  爱一瞬间的悲伤
    2021-02-11 17:18

    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) + ",";
    

    0 讨论(0)
提交回复
热议问题