49
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.

3
  • Don't forget about StringBuilder. That contains several useful things to do with Strings, very efficiently. See my answer below. Commented May 2, 2011 at 0:39
  • 2
    One line of code does not always mean it's efficient. Commented May 2, 2011 at 0:49
  • Do you want an efficient way to do it, or a short way (as in fewer lines of code) to do it? Commented May 2, 2011 at 1:20

11 Answers 11

85

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) + ",";
Sign up to request clarification or add additional context in comments.

2 Comments

I am roaming and seen this answer and wondering why count "1" is added? why not simply str.Remove(str.Length -1) to remove last char?
@A.T. I'm not too familiar with C#'s standard library, but looking at the documentation it seems that should work.
35

C# .NET makes it almost too easy.

str = str.TrimEnd('_')

4 Comments

It should be noted that this will only work when there's a single underscore at the end of the string, as TrimEnd will remove all occurrences of the character specified.
@Ohad Schneider: Not true - any number of the specified character will be trimmed off either end. But I notice I didn't answer the OP's question because I didn't see the comma he was trying to add. Therefore, I would edit my answer as: str = str.Trim('_') + ",";
TrimEnd will only remove trailing characters: msdn.microsoft.com/en-us/library/…
Your answer will not work for other characters and/or if there are multiple trailing _
8

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

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

Comments

7

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

Comments

7

Use the StringBuilder class

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

Comments

2

With one line of code you could write:

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

Comments

2

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

Comments

1

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.

Comments

1

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.

Comments

1
// 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] + ",";

2 Comments

This doesn't replace anything
@PanagiotisKanavos my bad. Answer has been edited.
0
//You mean like this? :D
string str = "Student_123_";
str = $"{str.Remove(str.Length -1)},";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.