String Comparison And Alphabetic Order of Individual Characters

后端 未结 4 1155
死守一世寂寞
死守一世寂寞 2021-02-18 23:06

I have a question related to string comparison vs. character comparison.

Characters > and 0 (zero) have following decimal values 62

相关标签:
4条回答
  • 2021-02-18 23:51

    it returns -1 because it is comparing str2 to str1, not the other way around. Eg, "is 48 equal to 62". No, it's less than 62 so it returns -1. It's semantically a little confusing when you read the parameter order

    0 讨论(0)
  • 2021-02-19 00:00

    The sort order of strings depends on the culture you use.

    StringComparer.CurrentCulture sorts the following 1-character strings as follows on my machine:

    ' -   ! " # $ % & (  ) * , . / : ; ? @ [
    \ ] ^ _ ` { | } ~ +  < = > 0 1 2 3 4 5 6
    7 8 9 a A b B c C d  D e E f F g G h H i
    I j J k K l L m M n  N o O p P q Q r R s
    S t T u U v V w W x  X y Y z Z
    

    StringComparer.Ordinal sorts the same strings as follows:

      ! " # $ % & ' ( )  * + , - . / 0 1 2 3
    4 5 6 7 8 9 : ; < =  > ? @ A B C D E F G
    H I J K L M N O P Q  R S T U V W X Y Z [
    \ ] ^ _ ` a b c d e  f g h i j k l m n o
    p q r s t u v w x y  z { | } ~
    
    0 讨论(0)
  • 2021-02-19 00:05

    When you compare the characters '>' and '0', you are comparing their ordinal values.

    To get the same behaviour from a string comparison, supply the ordinal string comparison type:

      Console.WriteLine(string.Compare(">", "0", StringComparison.Ordinal));
      Console.WriteLine(string.Compare(">", "0", StringComparison.InvariantCulture));
      Console.WriteLine(string.Compare(">", "0", StringComparison.CurrentCulture));
    

    The current culture is used by default, which has a sorting order intended to sort strings 'alphabetically' rather in strictly lexical order, for some definition of alphabetically.

    0 讨论(0)
  • 2021-02-19 00:06

    It sounds like what you want is the comparison to not use culture-specific rules. Have you tried StringComparison.Ordinal:

    Console.WriteLine( string.Compare( ">", "0", StringComparison.Ordinal ) ); // returns a positive number
    
    0 讨论(0)
提交回复
热议问题