gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:29:54 24 4
gpt4 key购买 nike

所以,基本上我在练习一些算法。我想弄清楚为什么当我尝试设置 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;
}

最佳答案

why the following code is giving me an error when I try to set the value of 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类(class)。它允许您通过附加、删除或替换字符串中的字符来更改字符串的内容。

关于c# - 为什么不能设置循环算法的索引值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12694756/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com