我正在做一个简单的hang子手游戏。除了用户输入正确字符的部分以外,我已经完成了所有工作,解决方案中的相应字符应替换为前者。在位置x处替换字符串中的单个字符
首先,这里是我的代码:
private void checkIfLetterIsInWord(char letter)
{
if (currentWord != string.Empty)
{
if (this.currentWord.Contains(letter))
{
List<int> indices = new List<int>();
for (int x = 0; x < currentWord.Length; x++)
{
if (currentWord[x] == letter)
{
indices.Add(x);
}
}
this.enteredRightLetter(letter, indices);
}
else
{
this.enteredWrongLetter();
}
}
}
private void enteredRightLetter(char letter, List<int> indices)
{
foreach (int i in indices)
{
string temp = lblWord.Text;
temp[i] = letter;
lblWord.Text = temp;
}
}
所以我的问题是该行
temp[i] = letter;
我来到这里的错误,指出“属性或索引不能被分配到 - 它是只读只要”。我已经搜索了一下,发现在运行时不能修改字符串。但我不知道如何替换包含猜测的标签。标签的格式是
_ _ _ _ _ _ _ //single char + space
任何人都可以给我一个提示,我可以如何用猜测的字符替换解决方案中的字符?
非常感谢,它的工作方式。有没有任何理由为什么字符串是不可改变的? – LeonidasFett
字符串不可变的一些原因是:线程安全性,积极的编译器优化和内存保存(例如快速复制),副作用预防(例如字典) –