Amrit
Amrit

Reputation: 23

How to validate c# code for specific alphabets only? e.g., the user should input only A or S or B and that too without regex and using if statement

I was trying to validate a C# code for allowing only specific characters to be considered in and if the user enters anything besides the specified, it pops up with invaid and returns.

    Console.WriteLine("Plan: ");
    string Plan = Console.ReadLine();

    if (Plan.length==0 || ! Plan._______("S") || ! Plan._______("M"))
    {
        Console.WriteLine("Invalid. Enter only "S" or "M");
    }

I can't figure out out what to put in that empty lines. .ToUpper() doesn't help or maybe I am doing it wrong. Any help will be apppreciated.

Upvotes: 0

Views: 84

Answers (2)

Noctis
Noctis

Reputation: 11763

Make your life easier. Do something like the following:

string[] valid_array = new string[] {"s","m"};

string input = Console.ReadLine();

if (valid_array.Any( c => string.Compare(input, c, ignoreCase: true) == 0) )
{
    // valid stuff, do something here
}
else
{
    // invalid stuff, do something here
}

Now, if you need new options, just add them to your valid string array.

Upvotes: 1

Backs
Backs

Reputation: 24903

if (Plan.length == 0 || (Plan != "S" && Plan != "M"))
{
    Console.WriteLine("Invalid. Enter only \"S\" or \"M\");
}

Upvotes: 0

Related Questions