user4291582
user4291582

Reputation:

C# ignoring letter case for if statement

I have this if statement:

if (input == 'day')
    Console.Write({0}, dayData);

When the user types 'day' it should be so that the console writes the data in that array. It works fine but is there anyway to get it to work if the user types 'DaY' or 'dAy' etc. I know I could do:

if (input == 'day' || input == 'dAy' || input == 'DaY')
     Console.WriteLine({0}, dayData);

But is there anyway to make it shorter and tidier? Thanks.

Upvotes: 7

Views: 6018

Answers (5)

Millie Smith
Millie Smith

Reputation: 4604

if (input.ToLower() == "day") { }

If your code is international, you are writing a library, you want a small speed boost, you are doing this in a loop or with large strings, et cetera, use the following:

if (input.Equals("day", StringComparison.OrdinalIgnoreCase)) { }

Or to use a specific international culture:

if (string.Compare(input, "day", true, new CultureInfo("de-DE")) == 0) { }

Upvotes: 11

user4632995
user4632995

Reputation:

Another way is

if(str1.Equals(str2, StringComparison.InvariantCultureIgnoreCase))
{
    //...
}

Second parameter allow you use one of six predefined comparison modes.

Upvotes: 1

Justin
Justin

Reputation: 424

You mention an array so I'll assume you're entering multiple things simultaneously (like 'day', 'dAy', etc)

foreach (var item in input)
{
    if (item.ToLower() == "day")
    {
        Console.WriteLine("{0}", item);
        break;
    }
}

edit: this would check each item in the array, write to the console, then stop if one was "day".

Upvotes: 1

Felipe Oriani
Felipe Oriani

Reputation: 38608

The string.Equals method allow you could to check the content of the string and ignore the case, for sample:

if (input.Equals("day", StringComparison.OrdinalIgnoreCase))
{

}

Upvotes: 2

Juan
Juan

Reputation: 3705

The string.Equals method allow you to set up configuration on the comparison and you can set it up to ignore case.

if (string.Equals(input, "day", StringComparison.InvariantCultureIgnoreCase))

Upvotes: 13

Related Questions