当前位置: 动力学知识库 > 问答 > 编程问答 >

substring - 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.

example with the word NAME:

  1. enter the letter E
  2. letter is in word -last position (4th)

example HELP

  1. Enter the letter V letter is not inside the word Add the letter to a

    list (list with wrong letters)

Thanks for your help;)

网友答案:

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:

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();

            }
        }
    }
}
网友答案:

You can use string.IndexOf:

string hangmanWord = "Democracy";
int index = hangmanWord.IndexOf("m"); // 2 (at position 2)
int index = hangmanWord.IndexOf("x"); // -1 (not found)
分享给朋友:
您可能感兴趣的文章:
随机阅读: