How to change 1 char in the string?

后端 未结 7 1791
天涯浪人
天涯浪人 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条回答
  •  隐瞒了意图╮
    2021-01-03 18:14

    Merged Chuck Norris's answer w/ Paulo Mendonça's using extensions methods:

    /// 
    /// Replace a string char at index with another char
    /// 
    /// string to be replaced
    /// position of the char to be replaced
    /// replacement char
    public static string ReplaceAtIndex(this string text, int index, char c)
    {
        var stringBuilder = new StringBuilder(text);
        stringBuilder[index] = c;
        return stringBuilder.ToString();
    }
    

提交回复
热议问题