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条回答
We Are One
2楼-- · 2020-06-07 04:22

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) + ",";
查看更多
该账号已被封号
3楼-- · 2020-06-07 04:24

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.

查看更多
地球回转人心会变
4楼-- · 2020-06-07 04:25

Use the StringBuilder class

                    StringBuilder mbuilder = new StringBuilder("Student_123_");

        mbuilder[mbuilder.Length-1] = ',';

        Console.WriteLine(mbuilder.ToString());
查看更多
混吃等死
5楼-- · 2020-06-07 04:27

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

str = Regex.Replace(str, ".$", ",");
查看更多
beautiful°
6楼-- · 2020-06-07 04:29

C# .NET makes it almost too easy.

str = str.TrimEnd('_')
查看更多
走好不送
7楼-- · 2020-06-07 04:30

With one line of code you could write:

str = str.Remove(str.Length - 1, 1) + ",";
查看更多
登录 后发表回答