首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java compareTo一步一步执行

Java compareTo一步一步执行
EN

Stack Overflow用户
提问于 2017-03-23 06:51:35
回答 2查看 378关注 0票数 1

我的基本理解是,Java compareTo方法lexicographically compares有两个字符串。我在这里读过一些基本知识,String Comparison in Java

我有以下例子:

代码语言:javascript
复制
public class CompareTo {
   public static void main(String args[]) {
       String str1 = "String";
       String str2 = "compareTo";
       String str3 = "String";
       int var1 = str1.compareTo( str2 );
       System.out.println("str1 & str2 comparison: "+var1);

       int var2 = str1.compareTo( str3 );
       System.out.println("str1 & str3 comparison: "+var2);
   }
}

我得到了var1 = -16var2 = 0

如果有人一步一步地向我解释这个Lexicographic comparison,那会有很大的帮助。

谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-03-23 06:54:41

好吧,如果你打印:

代码语言:javascript
复制
System.out.println ('S'-'c');

你得到了-16

StringcompareTo一次比较两个String的一个字符。第一对不相等的字符(在您的例子中是“字符串”的“S”和“compareTo”的“c”)决定结果。由于按字母顺序“S”位于'c‘之前,这个比较返回一个负值,这意味着"String“应该在"compareTo”之前。

在第二个比较中,所有对字符都是相等的,因此compareTo返回0。

票数 1
EN

Stack Overflow用户

发布于 2017-03-23 07:02:16

来自Java DOC

代码语言:javascript
复制
public int compareTo(String anotherString)
Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true.
This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. 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()

在ASCII表c= 99 (小数)和S= 83 (小数)中

对此:S= -16

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42969114

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档