[英]C# count if a imputfield letter is in a word
How can i count if a value, from a input box, is in an verb that's in a string? 如何计算输入框中的值是否在字符串的动词中?
And if possible, give the right position of the letter in the verb (like hangman) Also, if a verb is not containing a letter, place that letter on a list. 并尽可能在动词中给出字母的正确位置(例如hangman)。此外,如果动词中不包含字母,则将该字母放在列表中。
example with the word NAME: 单词“ NAME”的示例:
example HELP 例子帮助
Thanks for your help;) 谢谢你的帮助;)
You can use string.IndexOf: 您可以使用string.IndexOf:
string hangmanWord = "Democracy";
int index = hangmanWord.IndexOf("m"); // 2 (at position 2)
int index = hangmanWord.IndexOf("x"); // -1 (not found)
Would regular expressions be a better choice? 正则表达式会是更好的选择吗? You get all the occurrences of a letter as well as if the letter does not appear at all in the string (the test is in a console application - make sure you use System.Text.RegularExpressions
namespace): EDIT: Included the Hangman class and a simple console call: 您将获得所有出现的字母以及该字母完全不在字符串中出现的情况(测试在控制台应用程序中-确保使用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);
}
}
}
}
and the main program: 和主程序:
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.