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?

Cédric Bignon
  • 12,892
  • 3
  • 39
  • 51
LeonidasFett
  • 3,052
  • 4
  • 46
  • 76

3 Answers3

2

String is immutable class, so use StringBuilder instead:

  ...
      StringBuilder temp = new StringBuilder(lblWord.Text);
      temp[i] = letter; // <- It is possible here
      lblWord.Text = temp.ToString();  
  ...
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • many thanks, it works this way. Is there any reason why strings are immutable? – LeonidasFett Jul 25 '13 at 13:56
  • 1
    Some reasons for string being immutable are: thread safety, aggressive compiler optimization and memory saving (e.g. fast copy), side effects prevention (e.g. Dictionaries) – Dmitry Bychenko Jul 25 '13 at 14:01
2

The StringBuilder solution is good, but I think it is overkill. You can instead do this with toCharArray(). Also you don't need to update the label until the end of your loop.

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);
}
Daniel Gimenez
  • 18,530
  • 3
  • 50
  • 70
1

Convert the string to a character array with String.ToCharArray(), make the changes and the convert it back to a string with "new String(char[])"

CamW
  • 3,223
  • 24
  • 34