1

C# Code :

public class Test
{
    public static void Main()
    {
        List<string> list = new List<string> { "johnsmith@mail.com", "john_newyork@mail.com", "john00@mail.com" };
        list.Sort();
        for(int i=0;i<list.Count;i++){
            Console.WriteLine(list[i]);
        }

    }
}

Result :

john_newyork@mail.com

john00@mail.com

johnsmith@mail.com

Java Code :

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        List<String> list = new ArrayList<String>();
        list.add("johnsmith@mail.com");
        list.add("john_newyork@mail.com");
        list.add("john00@mail.com");
        Collections.sort(list);
        System.out.println(list);
    }
}

Result :

[john00@mail.com, john_newyork@mail.com, johnsmith@mail.com]

Ascii value of '_' is 95 and ascii value of '0' is 48. So ideally '0' should come before '_' in string sorting. Why C# sort places '_' before '0'?

But when I tried comparing the characters '_' and '0'. Both the languages compare properly and keep '0' before '_'.

Console.WriteLine('0'>'_'); -> False (C#)
System.out.println('0'>'_'); -> false (Java)
soup_boy
  • 388
  • 4
  • 13

2 Answers2

2

To sort by the ASCII value, use StringComparer.Ordinal

list.Sort(StringComparer.Ordinal);

  • Thanks. How does list.sort() work by default without any StringComparer? – soup_boy Nov 24 '19 at 09:28
  • 2
    @soup_boy It'd be the same as if you'd called `list.Sort(StringComparer.CurrentCulture)` – Powerlord Nov 24 '19 at 09:42
  • Incidentally, you can change Java to sort by culture info, but Java doesn't seem to have any constants for `Comparator`, so you'd have to implement your own that uses `java.text.Collator` (use its .`getInstance` methods) to do the string comparisons. – Powerlord Nov 24 '19 at 09:44
  • I faced the same problem at leetcode thanks a lot – Barış Can Yılmaz Dec 10 '22 at 20:18
0

In c# you can use a StringComparer to specify how the comparison between the strings should work. To achieve the same behaviour as in Java you need to use StringComparer.Ordinal.

using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    public class Test
    {
        public static void Main()
        {
            var list = new List<string> { "johnsmith@mail.com", "john_newyork@mail.com", "john00@mail.com" };
            list.Sort(StringComparer.Ordinal);
            foreach (var element in list)
            {
                Console.WriteLine(element);
            }
        }
    }
}

This prints the following on the console:

john00@mail.com
john_newyork@mail.com
johnsmith@mail.com

See also the documentation on Microsoft Docs for an extensive example:

Marius
  • 1,529
  • 6
  • 21