[英]C# count if a imputfield letter is in a word
如何計算輸入框中的值是否在字符串的動詞中?
並盡可能在動詞中給出字母的正確位置(例如hangman)。此外,如果動詞中不包含字母,則將該字母放在列表中。
單詞“ NAME”的示例:
例子幫助
謝謝你的幫助;)
您可以使用string.IndexOf:
string hangmanWord = "Democracy";
int index = hangmanWord.IndexOf("m"); // 2 (at position 2)
int index = hangmanWord.IndexOf("x"); // -1 (not found)
正則表達式會是更好的選擇嗎? 您將獲得所有出現的字母以及該字母完全不在字符串中出現的情況(測試在控制台應用程序中-確保使用System.Text.RegularExpressions
命名空間):編輯:包括Hangman類和一個簡單的控制台調用:
public class Hangman
{
public List<string> InvalidLetters { get; private set; }
private string input;
public Hangman(string input)
{
InvalidLetters = new List<string>();
this.input = input;
}
public void CheckLetter(string letter)
{
if (!Regex.IsMatch(input, letter, RegexOptions.IgnoreCase))
{
InvalidLetters.Add(letter);
Console.WriteLine("Letter " + letter + " does not appear in the string.");
}
else
{
MatchCollection coll = Regex.Matches(input, letter, RegexOptions.IgnoreCase);
Console.WriteLine("Letter " + letter + " appears in the following locations:");
foreach (Match m in coll)
{
Console.WriteLine(m.Index);
}
}
}
}
和主程序:
class Program
{
static void Main(string[] args)
{
string input = "Stack Overflow";
if (!string.IsNullOrEmpty(input))
{
Hangman h = new Hangman(input);
string letter = Console.ReadLine();
while (!string.IsNullOrEmpty(letter))
{
h.CheckLetter(letter);
letter = Console.ReadLine();
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.