Search code examples
c#stringstring-comparison

How to check two strings for difference in casing only?


Following pairs of string are possible. Now my goal is to detect only the casing difference in the first example:

  1. "abC","abc"
  2. "abc","abc"
  3. „abDef","abc"

My approach would be first to compare the strings with ignorecase = true in C#:

String.Compare(string1, string2, true) returns 0 for 1.+2. and returns 1 for the 3. possibility

So checking for 0 as result I can narrow down my results to two possibilities which I check now with ignorecase = false:

String.Compare(string1, string2, false)

So checking now for 0 would give me the right result. Is there any better solution to achieve this in one compare step?


Solution

  • String.Compare exists to cover the reverse scenario you have suggested, but in the context of sorting scenarios, you can use it for equality using == 0 or inequality !=0

    String.Equals performs the same evaluation logic as String.Compare, but specifically for equality scenarios.

    The issue in your case of detecting in-equality based only on casing means that you will have to do it in two checks, otherwise the strings not equalling at all would return a false negative response.

    The following options come to mind:

    public static bool IsSimilarButDifferentCase(string input1, string input2)
    {
        // satisfy the first criteria
        if (input1.Equals(intput2, StringComparison.InvariantCultureIgnoreCase))
        {
            // check that it is now NOT the same
            return !input1.Equals(intput2, StringComparison.InvariantCulture)
        }
        return false;
    }
    

    You could also do the following inline by converting to the lower (or upper case) and using the comparison operators directly:

    input1.ToLower() == input2.ToLower() && input1 != input2
    

    Feel free to us different culture overloads or variations to all the above as your business needs dictate.