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.
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.
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.
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();
}
if(input.StartWith("20") && input.Length >= 2)
{
Console.WriteLine("Valid Input");
}
else
{
Console.WriteLine("Not Valid");
}