0

I am doing a simple hangman game. I have gotten everything going except for the part where the user enters a correct char and the corresponding char in the solution word should be replaced with the former.

First, here is my code:

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;

    }
}

So my problem is the line

temp[i] = letter;

I get an error here that says "Property or indexer cannot be assigned to — it is read only". I have already googled and found out that strings cannot be modified during runtime. But I have no idea how to substitute the Label which contains the guesses. The label is in the format

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

Can anybody give me a hint how I can replace the chars in the solution word with the guessed chars?

4

3 回答 3

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);
}
于 2013-07-25T13:57:10.387 回答
2

String 是不可变类,因此请改用StringBuilder

  ...
      StringBuilder temp = new StringBuilder(lblWord.Text);
      temp[i] = letter; // <- It is possible here
      lblWord.Text = temp.ToString();  
  ...
于 2013-07-25T13:51:40.913 回答
1

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

于 2013-07-25T13:48:01.050 回答