String.CompareTo()返回意外值 [英] String.CompareTo() returns unexpected value

查看:108
本文介绍了String.CompareTo()返回意外值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用string.CompareTo()比较两个字符串进行排序时,出现了意想不到的结果。



在主方法中粘贴下面的代码。



While comparing two strings for sorting using string.CompareTo(), unexpected result comes.

Paste below code in the main method.

String str9 = "Output 9";
String str11 = "Output 11";

int nine_11 = str9.CompareTo(str11);





返回的值是一(1)表示str9大于str11。但是,我原以为-1。



任何想法都可以解决这个问题。



The value returned is one(1) means str9 is greater than str11. However, I was expecting it to be -1.

Any idea to overcome this.

推荐答案

这是正确的,它被称为词典比较。正如 Richard 指出的那样,字符'1'小于字符'9'。

您(可能)期望的是组合比较,即标题上的词典字符串(即输出)和尾随的数字(9,11)。这不是自动的,你必须自己编写一些(简单的)代码。
That is correct, it is called lexicographic comparison. As Richard pointed out, the character '1' is less than character '9'.
What you (possibly) expected was a combined compare, that is lexicographic on the heading strings (that is "Output ") and numeric on the trailing ones ( "9", "11"). That is not automatic you have to write yourself some (simple) code.


这篇关于String.CompareTo()返回意外值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆