How to change 1 char in the string?

后端 未结 7 1892
天涯浪人
天涯浪人 2021-01-03 17:43

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:



        
7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-03 17:49

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

提交回复
热议问题