简体   繁体   English

检查字符串中的字母

[英]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. 我正在WPF中用C#制作一个Hangman游戏,我想知道是否有一种方法可以检查字符串中的字母,以便如果选择了字母,程序就可以确定该字母是否在所选单词中。 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. 您可以使用Contains() ,但这将区分大小写。 Hangman is not. 子手不是。

The easiest way to handle that is to use IndexOf() instead: 处理该问题的最简单方法是使用IndexOf()

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 : 如果您还想知道字母首出现在单词中的哪个位置,可以使用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 . 您可以使用String.Contais方法 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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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