Compare strings in C# in switch-case block with different casing

Viewed 2117

I have a set of switch-case statements, such as "Hello, how are you", "Hi, how can I help you?". If the input from the user is verbatim i.e: "Hello, how are you", the match works.

But if the user entered "Hello, How are You", the match fails.

I would like if the user's input is the same but different casing then it should match. i.e.

"Hello, how are you" == "Hello, How are You" == "HELLO, how are YOU"

How can this be accomplished?

4 Answers

If you are using C# 7.0 or newer then you can use Pattern Matching with switch..case like below.

string a = "Hello, How are You";

switch (a)
{
    case string str when str.Equals("hello, how are you", StringComparison.InvariantCultureIgnoreCase):
        // Your code
        break;
    default:
        // default code
        break;

}

The switch handler in C# for strings is limited to exact character matching. Ultimately there are three approaches here:

  • use if, not a switch, and make use of manual string equality tests - perhaps specifying a StringComparison for case insensitivity
  • create a dictionary (perhaps static) with a case insensitive key comparer; put your expected strings in the dictionary - perhaps mapping to a private enum output, then switch on that output
  • use ToLower[Invariant] in the switch operand, and just eat the allocation

If it isn't high throughput, the last is probably fine

Just use ToLower on everything to do a non-case sensitive switch:

switch (myString.ToLower())
{
    case "hello, how are you":
        // do something
        break;
}

Instead of converting both strings to upper case or lower case and then comparing, you should use an equality comparison which can be made case-insensitive. For example:

String string1 = "Hello, how are you";
if (string1.Equals("Hello HOW are you", StringComparison.OrdinalIgnoreCase))
{
     ...
}
You should consider carefully exactly which rules are appropriate - ordinal, the current culture, the invariant culture, or possibly another culture entirely (e.g. using StringComparer.Create(culture, true)).
Related