简体   繁体   中英

Why is “Test” greater than “test”

using System;

public class Program
{
    public static void Main()
    {
        string t1, t2;
        t1 = "Test";
        t2 = "test";
        Console.WriteLine(t1.CompareTo(t2)); //prints 1, expected was -1
    }
} 

So, it says that CompareTo() is supposed to return 1 - if it's greater than, -1 if it's less than or 0 if it's equal to the other string. In this example I am comparing "Test" with "test". As I understood, in ASCII, 'A' < 'a'. So why does it say that t1 is greater if the only difference is first letter, and by ASCII, it should be smaller. Thanks.

The default C# string comparison (as in, if you don't specify it yourself anywhere) is a culture-aware comparison, and the rules depend on your computer's culture.

If you want to use ordinal comparison (ie ASCII as you call it, though C# strings are Unicode), you can use this instead:

Console.WriteLine(string.Compare(t1, t2, StringComparison.Ordinal));

Also note that the specification requires a negative, zero or positive result, not specifically -1. The command above will return -32 for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM