C#String.CompareTo不返回我期望的结果

Ale*_*lex 0 c# string comparison

我正在尝试比较小于等的字符串-以类似的方式比较数字。

我的问题是以下比较返回true:

var expectThisToBeFalse = "315160".CompareTo("40000") < 0;
Run Code Online (Sandbox Code Playgroud)

我知道我可以将它们作为数字进行比较,但是在我的应用程序中,我不知道它们是数字还是字母。

谁能解释我所错过的内容,以及是否有比较有效的比较方法

例如将显示:

“ 1”小于“ 2”

“ a”小于“ b”

“ aa”大于“ b”

等等...

Bog*_*cin 6

You are not missing anything. The metod you use compares two strings alphabetically. It means that if string A is in the alphabet ahead of string B, then it returns -1.

Because you're comparing two strings, not two numbers, the function looks at the first character of both of the strings ("3" and "4" in your example. Because "3" has a lower ASCII code than "4" (51 and 52, respectively), the function concludes that "315160" is ahead in the alphabet than "40000", so it returns -1. Because you compared the result of this function (-1) with 0, the variable is (correctly) true, because -1<0.

For what you wish, you will need to program your own function. I don't know if there is any function already programmed.

Later edit: more info on string.compare.

Later edit 2: something else struck me as interesting:

but in my application I do not know if they are numbers or letters.

为了解决此问题,您可以先检查两个输入是数字还是字母来开始。您会为自己省去很多麻烦,因为有时这两个输入将是数字,解决起来非常容易。

  • 出于同样的原因,“aa”将小于“b”,而不是更大,因为“aa”按字母顺序排在“b”之前。 (2认同)
  • “低位 ASCII 码”:不太正确。它执行“区分文化和区分大小写的比较”。因此,与不相关的字符集 (ASCII) 无关,也与 UTF-16 代码单元或 Unicode 代码点字典顺序不完全相关。它使用 [Unicode 语言环境数据](http://cldr.unicode.org/)。 (2认同)