Reputation: 521
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.
Upvotes: 49
Views: 119769
Reputation: 1
//You mean like this? :D
string str = "Student_123_";
str = $"{str.Remove(str.Length -1)},";
Upvotes: 0
Reputation: 13
// As string is array of chars you can use efficient "range" operator introduced in c# 8.0
string str = "Student_123_";
str = str[0..^1] + ",";
Upvotes: 1
Reputation: 5529
Use the StringBuilder class
StringBuilder mbuilder = new StringBuilder("Student_123_");
mbuilder[mbuilder.Length-1] = ',';
Console.WriteLine(mbuilder.ToString());
Upvotes: 7
Reputation: 1620
Elegant but not very efficient. Replaces any character at the end of str with a comma.
str = Regex.Replace(str, ".$", ",");
Upvotes: 8
Reputation: 117681
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) + ",";
Upvotes: 85
Reputation: 67193
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) + ",";
Upvotes: 7
Reputation: 27864
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.
Upvotes: 1
Reputation: 1043
With one line of code you could write:
str = str.Remove(str.Length - 1, 1) + ",";
Upvotes: 2
Reputation: 6597
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.
Upvotes: 1