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