简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM