Is there an easy way to change a char in a string in C#?

后端 未结 8 1856
忘掉有多难
忘掉有多难 2020-12-10 16:02

I want to do this:

string s = \"abc\";
s[1] = \'x\';

and s will become \"axc\". However, it seems that string[i] only has a getter and has

相关标签:
8条回答
  • 2020-12-10 16:57

    I don't think you can do this in C#, as the string cannot be altered (just destroyed and recreated). Have a look at the StringBuilder class.

    0 讨论(0)
  • 2020-12-10 16:58

    Strings are immutable, so you have to make a char[] array, change it, then make it back into a string:

    string s = "foo";
    char[] arr = s.ToCharArray();
    arr[1] = 'x';
    s = new string(arr);
    
    0 讨论(0)
提交回复
热议问题