Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding String Comparison behaviour

Tags:

c#

I'm need to convert some string comparisons from vb to c#. The vb code uses > and < operators. I am looking to replace this with standard framework string comparison methods. But, there's a behaviour I don't understand. To replicate this, I have this test

[TestMethod]
public void TestMethod2()
{
    string originalCulture = CultureInfo.CurrentCulture.Name; // en-GB

    var a = "d".CompareTo("t");  // returns -1
    var b = "T".CompareTo("t");  // returns 1

    Assert.IsTrue(a < 0, "Case 1");
    Assert.IsTrue(b <= 0, "Case 2");
}

Could someone explain why b is returning 1. My current understanding is that if it is case sensitive then "T" should precede "t" in the sort order i.e. -1. If it is case insensitive it would be the same i.e. 0

(FYI .Net Framework 4.5.2)

Many thx

like image 302
Simon Woods Avatar asked Jul 21 '17 10:07

Simon Woods


1 Answers

Lower case comes before upper case . That's true both for en-GB and for InvariantCulture.

If you want to the ASCII like behavior you should specify the additional CompareOptions.Ordinal parameter

See the following:

  • Difference between InvariantCulture and Ordinal string comparison

  • C# sorting strings small and capital letters

Sample code on repl.it:

using System;
using System.Globalization;
using System.Collections.Generic;

class MainClass
{
    public static void Main(string[] args)
    {

        //All the following case sensitive comparisons puts d before D
        Console.WriteLine("D".CompareTo("d"));
        Console.WriteLine(String.Compare("D", "d", false));
        Console.WriteLine(String.Compare("D", "d", false, CultureInfo.InvariantCulture));

        //All the following case sensitive comparisons puts capital D before small letter d
        Console.WriteLine(String.Compare("D", "d", CultureInfo.InvariantCulture, CompareOptions.Ordinal));

        //The following is case insensitive
        Console.WriteLine(String.Compare("D", "d", true));

        //The default string ordering in my case is d before D
        var list = new List<string>(new[] { "D", "d" });
        list.Sort();
        foreach (var s in list)
        {
            Console.WriteLine(s);
        }
    }
}

//Results on repl.it
//Mono C# compiler version 4.0.4.0
//   
//1
//1
//1
//-32
//0
//d
//D

Good luck

Eyal

like image 135
Eyal Liebermann Avatar answered Oct 16 '22 13:10

Eyal Liebermann