Question

I have made the following code:

string fname;
Console.WriteLine("Input  employee first name:");
fname = Console.ReadLine();

The idea is to insert a while loop (with an "if" in it) to limit the input from the console to alphabetical letters only. However, using Tryparse doesn't work since it parses strings to ints. I would be grateful to receive suggestions on how to resolve this issue by "Tryparsing" strings to strings.

Was it helpful?

Solution 2

As someone mentioned in the comments on your question, a RegEx would probably be the simplest way to evaluate the input

if (Regex.IsMatch("yourtexthere", "^[a-zA-Z]{1,25}$").Success) {
    // it matches                
}

That should give you a good idea of how to accomplish it

OTHER TIPS

Try this:

    Console.Write("Input  employee first name: ");
    var s = new StringBuilder();
    do
    {
        var key = Console.ReadKey(true);
        if (key.KeyChar == '\r')
            break;

        if (char.IsLetter(key.KeyChar))
        {
            Console.Write(key.KeyChar);
            s.Append(key.KeyChar);
        }
    } while (true);

    Console.WriteLine();
    Console.WriteLine( "You typed " + s.ToString());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top