How to replace last character of the string using

2020-06-07 04:14发布

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#
9条回答
Rolldiameter
2楼-- · 2020-06-07 04:35

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

查看更多
贼婆χ
3楼-- · 2020-06-07 04:37

Well, what you have won't work because str.Remove(...) doesn't manipulate str, it returns a new string with the removal operation completed on it.

So - you need:

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

In terms of efficiency, there are several other choices you could make (substring, trim ...) but ultimately you're going to get the same time/space complexity.

EDIT:

Also, don't try to squash everything into one line, the programmers who come after you will appreciate the greater readability. (Although in this case a single line is just as easy to read.) One line != more efficient.

查看更多
\"骚年 ilove
4楼-- · 2020-06-07 04:44

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) + ",";
查看更多
登录 后发表回答