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.
str = str.Substring(0, str.Length-1) + ",";
Well, what you have won't work because
str.Remove(...)
doesn't manipulatestr
, it returns a new string with the removal operation completed on it.So - you need:
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.
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: