为什么 System.out.println("0:00".compareTo("0"));结果 3?
Why does System.out.println("0:00".compareTo("0")); result in 3?
我很好奇
为什么 System.out.println("0:00".compareTo("0"));
结果 3?我期望 10 作为 : 58 的 ASCII 代码,而 0 的 ASCII 代码是 48。
请阅读文档 String.compareTo
:
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#compareTo(java.lang.String)
If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two string -- that is, the value:
this.charAt(k)-anotherString.charAt(k)
If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings -- that is, the value:
this.length()-anotherString.length()
第一个字符串的第一个字符等于整个第二个字符串 ("0"
)。因此,它们是通过长度来比较的。第一个字符串是 4 个字符长,第二个是 1。因此差异是 3
我很好奇
为什么 System.out.println("0:00".compareTo("0")); 结果 3?我期望 10 作为 : 58 的 ASCII 代码,而 0 的 ASCII 代码是 48。
请阅读文档 String.compareTo
:
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#compareTo(java.lang.String)
If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two string -- that is, the value:
this.charAt(k)-anotherString.charAt(k)
If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings -- that is, the value:
this.length()-anotherString.length()
第一个字符串的第一个字符等于整个第二个字符串 ("0"
)。因此,它们是通过长度来比较的。第一个字符串是 4 个字符长,第二个是 1。因此差异是 3