手动计算字符串 compareTo 字符串的输出

Manually calculate output from string compareTo string

我正在尝试了解如何在比较字符串时手动计算输出,因为我正在练习的过去的论文中出现过类似的问题。

我知道,如果字符串按字典顺序(根据 unicode)在参数字符串之前,则结果为负,如果它在参数字符串之后,则结果为正,如果它们相等,则结果为零。我不知道如何计算值(超出符号)。

我有给出输出 1、-1、-3、3 的代码。我明白为什么每个都是正数或负数,但不知道为什么是 1 或 3。

public class CompareToPractice {
    public static void main(String[] args) {
        String str1 = "bode";
        String str2 = "bod";
        String str3 = "bodge";
        String str4 = "bog";

        int result1 = str1.compareTo(str2);
        System.out.println(result1);
        int result2 = str2.compareTo(str1);
        System.out.println(result2);
        int result3 = str3.compareTo(str4);
        System.out.println(result3);
        int result4 = str4.compareTo(str3);
        System.out.println(result4);
    }
}

谢谢

是字符'd'和'e'的区别(ascii区别)。

这是compareTo的代码

public int compareTo(String anotherString) {
    int len1 = value.length;
    int len2 = anotherString.value.length;
    int lim = Math.min(len1, len2);
    char v1[] = value;
    char v2[] = anotherString.value;

    int k = 0;
    while (k < lim) {
       char c1 = v1[k];
       char c2 = v2[k];
       if (c1 != c2) {
           return c1 - c2;
       }
       k++;
    }
    return len1 - len2;
}

从第 if (c1 != c2) 行可以看出。如果 2 个字符不相等,则结果将是这 2 个值的减法。

在你的例子中 str3.compareTo(str4) 是 "bodge" - "bog"。
所以'd'-'g'(ASCII值:100 - 103 = -3)

I don't see how to calculate the value (beyond the sign).

值 "beyond the sign" 无关紧要。它不传达普通应用程序可以使用 1 的信息。这仅仅是一个实现细节:针对速度进行了优化的算法的意外产物。

如果你真的想知道,请看source code


1 - 好吧,我想你理论上可以构建一个使用它的程序。但是我无法想象这样一个程序可以解决的问题......除了循环问题,例如调查 compareTo!

的统计属性

compareTo 的文档清楚地定义了在什么情况下计算结果以及如何计算结果。

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()

Bandi Kishore 的回答也解释了 ASCII 差异计算: