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

时间:2012-10-02 16:54:28

标签: 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;
}

3 个答案:

答案 0 :(得分: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;

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

答案 1 :(得分:1)

因为number是空字符串。改为使用连接运算符:

number = number + randomness[i];

答案 2 :(得分:1)

好的,如果您正在尝试执行字符串连接,请将其更改为:

public int SumOfRandomNumbersWithStrings(string randomness) 
{ 
    StringBuilder sb = new StringBuilder();

    //Get the value of each index in the array 
    for (int i = 0; i < randomness.Length; i++) 
    { 
        sb.Append(randomness[i]);
    } 

    //temporarily one until I finish the algorithm 
    return 1; 
} 

但是,如果您尝试使用number构建数组,那么让我们将其更改为:

public int SumOfRandomNumbersWithStrings(string randomness) 
{ 
    //Get the value of each index in the array 
    char[] number = new char[randomness.Length]; 
    for (int i = 0; i < randomness.Length; i++) 
    { 
        number[i] = randomness[i]; 
    } 

    //temporarily one until I finish the algorithm 
    return 1; 
}