How to change 1 char in the string?

[Originally Posted By]:

I have a next code:

string str = "valta is the best place in the World";

And i need to replace the first symbol, i do so:

str[0] = 'M';

But I recieve an error. How can I do this?


Strings are immutable, meaning you can’t change a character. Instead, you create new strings.

What you are asking can be done several ways. The most appropriate solution will vary depending on the nature of the changes you are making to the original string. Are you changing only one character? Do you need to insert/delete/append?

Here are a couple ways to create a new string from an existing string, but having a different first character:

str = 'M' + str.Remove(0, 1);

str = 'M' + str.Substring(1);

Above, the new string is assigned to the original variable, str.

I’d like to add that the answers from others demonstrating StringBuilder are also very appropriate. I wouldn’t instantiate a StringBuilder to change one character, but if many changes are needed StringBuilder is a better solution than my examples which create a temporary new string in the process. StringBuilder provides a mutable object that allows many changes and/or append operations. Once you are done making changes, an immutable string is created from the StringBuilder with the .ToString() method. You can continue to make changes on the StringBuilder object and create more new strings, as needed, using .ToString().


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s