📜  java字符串之compareto

📅  最后修改于: 2020-09-26 05:47:53             🧑  作者: Mango

Java字符串compareTo()

Java 字符串 compareTo()方法按字典顺序将给定字符串与当前字符串进行比较。返回正数,负数或0。

它根据字符串中每个字符的Unicode值比较字符串。

如果第一个字符串在字典上大于第二个字符串,则返回正数(字符值的差)。如果第一个字符串在字典上小于第二个字符串 ,则返回负数;如果第一个字符串在字典上等于第二个字符串,则返回0。

 if s1 > s2, it returns positive number
if s1 < s2, it returns negative number
if s1 == s2, it returns 0

内部实现

 public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String) anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                            return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

Signature(签名)

 public int compareTo(String anotherString)

参数

anotherString:代表字符串,它是与当前字符串进行比较

返回值或类型

整数值

Java字符串compareTo()方法示例

 public class CompareToExample{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="meklo";
String s4="hemlo";
String s5="flag";
System.out.println(s1.compareTo(s2));//0 because both are equal
System.out.println(s1.compareTo(s3));//-5 because "h" is 5 times lower than "m"
System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times lower than "m"
System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f"
}}

输出:

 0
-5
-1
2

Java字符串compareTo():空字符串

如果将字符串与空白或空字符串进行比较,它将返回字符串的长度。如果第二个字符串为空,则结果为正。如果第一个字符串为空,则结果为负。

 public class CompareToExample2{
public static void main(String args[]){
String s1="hello";
String s2="";
String s3="me";
System.out.println(s1.compareTo(s2));
System.out.println(s2.compareTo(s3));
}}

输出:

 5
-2