所以,基本上我是在练习一些算法。当我尝试设置numberi的值时,我正在尝试弄清楚为什么下面的代码给我一个错误?我知道这可能很简单,但我不知道为什么它不起作用。
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;
}发布于 2012-10-03 00:57:19
当我尝试设置Numer值时,以下代码显示错误的原因
因为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类。它允许您通过附加、删除或替换字符串中的字符来更改字符串的内容。
发布于 2012-10-03 00:55:47
因为number是空字符串。请改用连接运算符:
number = number + randomness[i];发布于 2012-10-03 00:59:17
好的,如果你想执行字符串连接,我们把它改成这样:
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;
} https://stackoverflow.com/questions/12694756
复制相似问题