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

时间:2013-07-25 13:44:13

标签: c# string replace

我正在做一个简单的刽子手游戏。除了用户输入正确字符的部分以外,解决方案中的相应字符应该替换为前者。

首先,这是我的代码:

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;

我在此处收到错误消息“无法将属性或索引器分配给它 - 它是只读的”。我已经google了,发现在运行时不能修改字符串。但我不知道如何替换包含猜测的标签。标签的格式为

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

任何人都可以给我一个暗示我如何用猜测的字符替换解决方案中的字符?

3 个答案:

答案 0 :(得分:2)

String是 immutable 类,所以请改用 StringBuilder

  ...
      StringBuilder temp = new StringBuilder(lblWord.Text);
      temp[i] = letter; // <- It is possible here
      lblWord.Text = temp.ToString();  
  ...

答案 1 :(得分:2)

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);
}

答案 2 :(得分:1)

使用String.ToCharArray()将字符串转换为字符数组,进行更改并将其转换回带有“new String(char [])”的字符串