简体   繁体   中英

How do I compare two strings together to see if one is greater than the other(alphabetically)? c#

How do I compare two strings together to see if one is greater than the other(alphabetically)? for example if I were to compare b and a, a would be greater than b because it comes first in the alphabet.

This is what I am trying to compare:

if (StringArray[lower] <= StringArray[middle])

You can use String.Compare method.

var control = string.Compare("a", "b") > 0;

This will return false because b is greater than a , if you want to reverse it then change it like this:

var control = string.Compare("a", "b") < 0;

please check :

  {
    string a = "a"; // 1
    string b = "b"; // 2

    int c = string.Compare(a, b);
    Console.WriteLine(c);

    c = string.CompareOrdinal(b, a);
    Console.WriteLine(c);

    c = a.CompareTo(b);
    Console.WriteLine(c);

    c = b.CompareTo(a);
    Console.WriteLine(c);
    }

Output

-1       (This means a is smaller than b)
 1        (This means b is smaller than a)
-1
 1

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