如何更换使用C#字符串的最后一个字符? [英] How to replace last character of the string using c#?
问题描述
string str = "Student_123_";
我需要更换的最后一个字符_和,。我做了这个样子。
I need to replace the last character "_" with ",". I did it like this.
str.Remove(str.Length -1, 1);
str = str + ",";
但是,是它能够更有效地实现它。可能是一行代码。??
顺便说一句,最后一个字符可以是任何字符。所以在这里更换无法工作。
However, is it possible to achieve it more efficiently. may be one line of code.?? BTW, last character can be any character. So Replace wont work here.
推荐答案
没有。
在C#字符串是不可变的,因此你不能改变就地的字符串。您必须首先删除字符串的一部分,然后创建一个新的字符串。事实上,这也意味着你原来的代码是错误的,因为 str.Remove(str.Length -1,1);
不会改变海峡可言,它返回一个新的字符串!这应该做的:
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) + ",";
这篇关于如何更换使用C#字符串的最后一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!