Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace last character of the string using c#?

Tags:

c#

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.

like image 730
user732853 Avatar asked May 02 '11 00:05

user732853


People also ask

How can I remove last character from a string in C?

Every string in C ends with '\0'. So you need do this: int size = strlen(my_str); //Total size of string my_str[size-1] = '\0'; This way, you remove the last char.

What is the last element of string in C?

Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null. The following declaration and initialization create a string consisting of the word "Hello".

How do I remove the last 3 characters from a string?

Use the String. slice() method to remove the last 3 characters from a string, e.g. const withoutLast3 = str. slice(0, -3); . The slice method will return a new string that doesn't contain the last 3 characters of the original string.


1 Answers

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) + ","; 
like image 104
orlp Avatar answered Sep 28 '22 04:09

orlp