Reputation: 545
I am making a Hangman Game in C# in WPF, and I am wondering if there is a way to check what letters are in a string so that if a letter is choosen the program can determine if the letter is in the chosen word or not. Ex.
String StackOverFlow; //Sample String
//If Letter "A" is chosen,
private void AButt_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
//What Would I Put Here?
}
Upvotes: 0
Views: 707
Reputation:
You can use ToLower() first to tackle case-sensitivity:
StackOverflow.ToLower().Contains("a")
Upvotes: 1
Reputation: 7591
Use Contains:
StackOverFlow.Contains("A");
If you also want to know where in the word the letter first appears, you can use IndexOf:
StackOverFlow = "EXAMPLE"
StackOverFlow.IndexOf("A"); //returns 2
StackOverFlow.IndexOf("B"); //returns -1 because it is not present
Upvotes: 2
Reputation: 245419
You could use Contains()
, but that is going to be case sensitive. Hangman is not.
The easiest way to handle that is to use IndexOf()
instead:
if(StackOverFlow.IndexOf("A", StringComparison.CurrentCultureIgnoreCase) > -1)
{
// Found
}
else
{
// Not Found
}
Upvotes: 4
Reputation: 9399
You could use the String.Contais method. And don't create one event handler for each letter - create only one which checks what letter was input, then do something according to it existing in the string or not.
Upvotes: 2