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

匿名 (未验证) 提交于 2019-12-03 03:04:01

问题:

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.

回答1:

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


回答2:

C# .NET makes it almost too easy.

str = str.TrimEnd('_') 


回答3:

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


回答4:

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

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


回答5:

Use the StringBuilder class

                    StringBuilder mbuilder = new StringBuilder("Student_123_");          mbuilder[mbuilder.Length-1] = ',';          Console.WriteLine(mbuilder.ToString()); 


回答6:

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



回答7:

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.



回答8:

With one line of code you could write:

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


回答9:

str.Remove doesn't modify str, it returns a new string. Your first line should read str = str.Remove...

One line? OK: str = str.Remove(str.Length - 1) + ",";

I think that's as efficient as you're going to get. Technically, you are creating two new strings here, not one (The result of the Remove, and the result of the Concatenation). However, everything I can think of to not create two strings, ends up creating more than 1 other object to do so. You could use a StringBuilder, but that's heavier weight than an extra string, or perhaps a char[], but it's still an extra object, no better than what I have listed above.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!