test player
test player

Reputation: 331

How to check user input case insensitive

I have to find the square of a number / 12345 / - it's done. I wanted to make the program a bit more complicated and I have this:

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("The square of the number 12345 is");
        Console.WriteLine(Math.Sqrt(12345));
        Console.WriteLine("Enter a number to calculate the square:");
        int numVal = int.Parse(Console.ReadLine());
        Console.WriteLine("The square of your number is" + " " + Math.Sqrt(numVal));
        Console.WriteLine("Do you wish to enter another number? Yes / No");
        string input = Console.ReadLine();
            if (input == "Yes")
            {
                Console.WriteLine("Enter a number to calculate the square:");
                int newNum = int.Parse(Console.ReadLine());
                Console.WriteLine("The square of your number is" + " " + Math.Sqrt(newNum));
            }
            else
            {
                Console.WriteLine("Have a nice day!");
            }

    }
}

Now a have this problem: when the program asks if I want to enter another number, the answer should be with capital letter / Yes, No /. Is there a way to make it work even if I enter the answear with lower case / yes, no /?

Upvotes: 0

Views: 4199

Answers (3)

gkrishy
gkrishy

Reputation: 756

As per your input, below line will react.

if(string.Equals(input, "Yes", StringComparison.CurrentCultureIgnoreCase))
{
  // Your stuffs
}

or

if(string.Equals(input, "Yes", StringComparison.OrdinalIgnoreCase))
{
  // Your stuffs
}

Note: OrdinalIgnoreCase compares the character codes without cultural aspects. This is good for exact comparisons, like login names, but not for sorting strings with unusual characters like é or ö. This is also faster because there are no extra rules to apply before comparing.

For more info : Go Here or here

Upvotes: 2

Chris Bohatka
Chris Bohatka

Reputation: 363

string.Equals(input, "Yes", StringComparison.OrdinalIgnoreCase)

Upvotes: -2

apomene
apomene

Reputation: 14389

you can try:

...
string input = Console.ReadLine();
            if (input.ToUpper() == "YES")
            {
                ...

Upvotes: 1

Related Questions