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?
String are immutable in Java. You can't change them. You need to create a new string with the character replaced.
replace() method helps to replace the occurrence of the given old character with the new character or substring. The method contains the parameters like old(a character that you wish to replace), new(a new character you would like to replace with), and count(a number of times you want to replace the character).
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()
.
I suggest you to use StringBuilder
class for it and than parse it to string if you need.
System.Text.StringBuilder strBuilder = new System.Text.StringBuilder("valta is the best place in the World"); strBuilder[0] = 'M'; string str=strBuilder.ToString();
You can't change string's characters in this way, because in C# string isn't dynamic and is immutable and it's chars are readonly. For make sure in it try to use methods of string, for example, if you do str.ToLower()
it makes new string and your previous string doesn't change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With