字符串为负的String.Compare()错误 [英] String.Compare() bug with negative number string
问题描述
我测试了string.compare()并得到以下结果.有人可以验证吗?
``-''(破折号/减号)的ascii值为45.
0(零)的ascii值为48.
因此,-"小于任何数字.
每个测试应返回-1,但结果如下:
1. string.Compare(-1","2")返回-1
2. string.Compare(-2","2")返回1
3. string.Compare(-3","2")返回1
4. string.Compare(-1","22")返回-1
5. string.Compare(-2","22")返回-1
6. string.Compare(-3","22")返回1
似乎C#在比较时会忽略-".但是,如果是这样,则测试#2应该返回0.
I tested the string.compare() and got the following results. Can anyone verify it?
''-'' (dash/minus) has an ascii value of 45.
0 (zero) has ascii value of 48.
Therefore, ''-'' is less than any numeral digit.
Each test should return -1, but they comes out as below:
1. string.Compare("-1","2") returns -1
2. string.Compare("-2","2") returns 1
3. string.Compare("-3","2") returns 1
4. string.Compare("-1","22") returns -1
5. string.Compare("-2","22") returns -1
6. string.Compare("-3","22") returns 1
Seem like C# ignores the ''-'' when it compares. However, if that is true, then test #2 should return 0.
推荐答案
String.Compare
比较字符串,而不是数字.您看到-2和2返回1的原因是因为该语言试图确定将数字作为单词进行排序的位置.即,如果您尝试执行string.Compare("-a", "a");
,将会得到相同的结果.
如果比较数字,则应将其转换为数字.您可以尝试重载Compare
方法并将StringComparison.Ordinal
用作第三个参数,这应该可以解决问题.
有关MSDN的更多讨论 http://msdn.microsoft.com/zh-cn/library/system.globalization.compareoptions.aspx
戴夫
Hi,
String.Compare
compares strings, not numbers. The reason you are seeing the -2 and 2 returning 1 is because the language is trying to determine where the numbers fit in terms of sorting them as words. ie if you tried to dostring.Compare("-a", "a");
you will get the same result.
If comparing numbers, they should be converted to numbers. You can try to overload theCompare
method and using theStringComparison.Ordinal
as a third parameter and that should fix the problem.
There is more discussion on MSDN http://msdn.microsoft.com/en-us/library/system.globalization.compareoptions.aspx
Dave
感谢戴夫,
如果程序员打算比较两个数字,那么他/她将不会使用string.compare().比较两个字符串时,无论字符串内容如何,我都希望它们从左到右逐个字符地进行比较.
我很好奇为什么它们同时具有string.Compare()和string.CompareOrdinal().现在,我知道了原因.我喜欢了解string.Compare()行为背后的参数.您提供的链接已断开.你可以看看吗?
本.
Thank Dave,
If a programmer means to compare two numbers, he/she wouldn''t use string.compare(). When compare 2 strings, I would expect they to be compared character by character from left to right regardless of the string contents.
I was curious why they have both string.Compare() and string.CompareOrdinal(). Now, I know the reason. I love to understand the arguments behind string.Compare() behavior. The link you gave is broken. Can you look into that?
Ben.
这篇关于字符串为负的String.Compare()错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!