简体   繁体   中英

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?
} 

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
}

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

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.

您可以先使用ToLower()处理大小写敏感问题: StackOverflow.ToLower().Contains("a")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM