C# 替换位置x处字符串中的单个字符

C# 替换位置x处字符串中的单个字符,c#,string,replace,C#,String,Replace,我正在做一个简单的刽子手游戏。除了用户输入正确的字符和解决方案word中相应的字符应替换为前者的部分之外,我已经完成了所有工作 首先,这是我的代码: private void checkIfLetterIsInWord(char letter) { if (currentWord != string.Empty) { if (this.currentWord.Contains(letter)) { List<int&g

我正在做一个简单的刽子手游戏。除了用户输入正确的字符和解决方案word中相应的字符应替换为前者的部分之外,我已经完成了所有工作

首先,这是我的代码:

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;

    }
}
我在这里得到一个错误,说“属性或索引器不能被分配到-它是只读的”。我已经在谷歌上搜索过,发现字符串在运行时是不能修改的。但我不知道如何替换包含猜测的标签。标签的格式为

_ _ _ _ _ _ _ //single char + space

有人能给我一个提示,我如何用猜出来的字符替换解单词中的字符吗

使用string.tocharray()将字符串转换为字符数组,进行更改并将其转换回具有“new string(char[])的字符串。

使用string.tocharray()将字符串转换为字符数组,进行更改并将其转换回具有“new string(char[])的字符串。

字符串是不可变的类,因此,请改用StringBuilder:

。。。
StringBuilder temp=新的StringBuilder(lblWord.Text);
temp[i]=字母;// 字符串是不可变类,因此请改用StringBuilder:

。。。
StringBuilder temp=新的StringBuilder(lblWord.Text);

temp[i]=字母;//
StringBuilder
解决方案是好的,但我认为这太过分了。您可以使用
toCharArray()
执行此操作。此外,在循环结束之前,您不需要更新标签

private void enteredRightLetter(char letter, List<int> indices)
{
   char[] temp = lblWord.Text.ToCharArray();
   foreach (int i in indices)
   {
      temp[i] = letter;
   }
   lblWord.Text= new string(temp);
}
private void enteredRightLetter(字符字母,列表索引)
{
char[]temp=lblWord.Text.ToCharArray();
foreach(索引中的int i)
{
temp[i]=字母;
}
lblWord.Text=新字符串(临时);
}

StringBuilder的
解决方案很好,但我认为这太过分了。您可以使用
toCharArray()
执行此操作。此外,在循环结束之前,您不需要更新标签

private void enteredRightLetter(char letter, List<int> indices)
{
   char[] temp = lblWord.Text.ToCharArray();
   foreach (int i in indices)
   {
      temp[i] = letter;
   }
   lblWord.Text= new string(temp);
}
private void enteredRightLetter(字符字母,列表索引)
{
char[]temp=lblWord.Text.ToCharArray();
foreach(索引中的int i)
{
temp[i]=字母;
}
lblWord.Text=新字符串(临时);
}

非常感谢,它是这样工作的。字符串不可变有什么原因吗?字符串不可变的原因有:线程安全、积极的编译器优化和内存节省(如快速复制)、副作用预防(如字典)。非常感谢,它是这样工作的。字符串不可变有什么原因吗?字符串不可变的原因有:线程安全、积极的编译器优化和内存节省(如快速复制)、副作用预防(如字典)
private void enteredRightLetter(char letter, List<int> indices)
{
   char[] temp = lblWord.Text.ToCharArray();
   foreach (int i in indices)
   {
      temp[i] = letter;
   }
   lblWord.Text= new string(temp);
}