'How can i check my word for a specific letter from a user input?
I'm creating a hangman game how can I check my word for a specific letter from a user input? I know there isn't much code here but I'm stuck and cant quite find any answers to my problem
//word or phrase in variable
{
string word = "supercalifragilisticexpialidocious"
//blanked out word / phrase
string blanked = "___________________________________"
// #of incorrect guesses
int guesses = 6
// letter guesses
string letter_guess = input("enter a letter guess: ")
//start loop
while()
{
}
//if guess incorrect do this
// how do i check the var for correct letters
//elif guess correct do this
//elif out of guesses do this
//else do this
}
Solution 1:[1]
There are many ways to do this, I'm sure. This may not be the best approach, but below you will find one example.
Basically the approach is to convert your word into a character array. Then, loop through each character in the array and compare with letterGuess. As you will notice, TryParse is used here, this will take care of any unwanted input from the user.
If there is a match, blanked[i] = word[i]; will essentially replace the appropriate '_' blank character in blanked with the correct letter guess.
trys gets incremented when there is an incorrect guess. And the remaining bit determines a win or loss.
public static void Main()
{
char[] word = "Stackoverflow".ToLower().ToCharArray();
char[] blanked = "_____________".ToCharArray();
int wrongGuesses = 6;
int trys = 0;
while (blanked.Contains('_') & trys <= wrongGuesses)
{
Console.WriteLine("Enter a letter guess: ");
bool _ = char.TryParse(Console.ReadLine().ToLower(), out char letterGuess);
for (int i = 0; i < word.Length; i++)
{
if (word[i] == letterGuess)
{
blanked[i] = word[i];
}
}
if (!blanked.Contains(letterGuess))
{
trys++;
}
Console.WriteLine(blanked);
}
if (!blanked.Contains('_'))
{
Console.WriteLine("You won");
}
else
{
Console.WriteLine("You lose");
}
Console.ReadLine();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | The2Step |
