5

I have searched this site for similar questions and the ones I've found don't work for me. I apologize for asking if the answer is somewhere and I haven't been able to find it. Please let me know if I am doing something wrong by asking this.

I am making hangman in C#. What I've done is make it so that the program picks a random string from an array, makes an array of the guessed letters (which it initially fills with '_' for as long as the word is). It then is supposed to get a user's input for a letter, see if that letter is in the word, and if it is, add that letter to the guessed letters array. I am stuck at this part:

if (gameWord.Contains(guessedLetter)) 
{
    //for every character in gameWord
    for (int x = 0; x < gameWord.Length; x++)
    {
        //if the character at the 'x' position in gameWord is equal to the guessed letter
        if (gameWord[x] == guessedLetter)
        {
            //guessString at that x position is equal to the guessed letter
            guessString[x] = guessedLetter;
        }
    }

}

At "if (gameWord[x] == guessedLetter)" I am getting the error shown in the title.

gameWord is a string chosen from an array of strings, and guessedLetter is a string inputted by the user with Console.ReadLine();.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
user163505
  • 481
  • 3
  • 11
  • 22

3 Answers3

5

If guessedLetter is a string, then you need to change one type to the other. You could easily just get the first character of guessedLetter:

if (gameWord[x] == guessedLetter[0])

or call ToString() on gameWord[x] as the other answer suggests.

However, you are about to run into a much bigger problem. [] is a readonly operation (MSDN) since strings are immutable, so your next line (the assignment) will fail.

To do that, you'll need a StringBuilder:

StringBuilder sb = new StringBuilder(gameWord);
sb[index] = guessedLetter[0];
gameWord = sb.ToString();

Credit to Replacing a char at a given index in string? for that code.

Community
  • 1
  • 1
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
2

You need to compare values of the same type. When taking a character from gameWord, i.e. gameWord[x], that value is treated as a char.

guessedLetter also needs to be of type char in order for the comparison to work.

I am assuming that guessedLetter is of type string here.

Here is an example:

string gameWord = "Random"; 
char guessedLetter = char.Parse(Console.ReadLine());

for (int i=0; i < gameWord.length; i++) {
    if (gameWord[i] == guessedLetter)
        Console.WriteLine("Letter was found!"); 
}
Mirodinho
  • 1,171
  • 1
  • 13
  • 25
1

gameWord[x] is accessing a character of gameWord, so it's a character, not a string. You can convert it to string before comparison:

if (gameWord[x].ToString() == guessedLetter)
Phuong Nguyen
  • 2,960
  • 1
  • 16
  • 25