-1

I'm trying to validate input from a console input

The requirement is for the first 2 digits of the console input to be 20

I think

input[0] = '2' will validate that the first digit is a 2

What would the syntax for validating 20 be?

Thanks.

Noel ST
  • 45
  • 7

3 Answers3

3

Many ways to accomplish this, but I'd go with string method StartsWith:

var input = Console.ReadLine();

if(input.StartsWith("20"))
{

}

StartsWith will not throw if input is less than 2 characters, and Console.ReadLine (assuming that's what you are using) will, in all common user scenarios, not return null.

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
0

You can do it by

private static void Main(string[] args)
        {

        string s = Console.ReadLine();

        if (s.Length >= 2 && s.Substring(0, 2) == "20")
        {
            Console.WriteLine("Yes");
        }
        else
        {
            Console.WriteLine("No");
        }

        Console.ReadKey();
    }
Mostafiz
  • 7,243
  • 3
  • 28
  • 42
0
if(input.StartWith("20") && input.Length >= 2)
{
   Console.WriteLine("Valid Input");
}
else
{
   Console.WriteLine("Not Valid");
}
Lakhtey
  • 35
  • 1
  • 13