Praetor12 Praetor12 - 1 year ago 126
C# Question

How to change 1 char in the string?

I have this code:

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

I need to replace the first symbol. When I try this:

str[0] = 'M';

I received an error. How can I do this?

Answer Source

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().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download