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.
That's a limitation of working with
string
. You can useStringBuilder
if you need to do a lot of changes like this. But it's not worth it for the simple task you need.str.Remove
doesn't modifystr
, it returns a new string. Your first line should readstr = 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.Use the StringBuilder class
Elegant but not very efficient. Replaces any character at the end of str with a comma.
C# .NET makes it almost too easy.
With one line of code you could write: