为什么我不能设置循环算法的索引值?

Ray*_*awn 2 c# algorithm loops

所以,基本上我正在练习一些算法.我试图找出为什么下面的代码在我尝试设置number [i]的值时给我一个错误?我知道它可能很简单,但我不'为什么'它不起作用.

public int SumOfRandomNumbersWithStrings(string randomness)
{
    //Get the value of each index in the array
    string number = "";
    for (int i = 0; i < randomness.Length; i++)
    {
        number[i] = randomness[i];
    }
    //temporarily one until I finish the algorithm
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 5

为什么以下代码在我尝试设置number [i]的值时给出错误

因为C#中的字符串是不可变的.

但是,字符数组是可变的,所以你可以这样做:

char number[] = new char[randomness.Length];
for (int i = 0; i < randomness.Length; i++)
{
     number[i] = randomness[i];
}
string numStr = new string(number);
//temporarily one until I finish the algorithm
return 1;
Run Code Online (Sandbox Code Playgroud)

在C#中构建字符串的最常用方法是使用StringBuilder该类.它允许您通过追加,删除或替换字符串中的字符来更改字符串的内容.