Andrew
Andrew

Reputation: 545

Check What Letters are in a String

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

Answers (4)

user2237264
user2237264

Reputation:

You can use ToLower() first to tackle case-sensitivity: StackOverflow.ToLower().Contains("a")

Upvotes: 1

nmat
nmat

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

Justin Niessner
Justin Niessner

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

Geeky Guy
Geeky Guy

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

Related Questions