Java教程-Java 字符串比较

在 Java 中,我们可以使用不同的方式来比较 String 对象的内容和引用。
String 对象的比较通常用于身份验证(使用 equals() 方法)、排序(使用 compareTo() 方法)和引用匹配(使用 == 运算符)等操作。
下面是 Java 中比较 String 对象的三种方式:
- 通过使用 equals() 方法
- 通过使用 == 运算符
- 通过 compareTo() 方法
1) 通过使用 equals() 方法
String 类提供的 equals() 方法用于比较字符串的内容,即比较字符串的值是否相等。String 类具有以下两个 equals() 方法:
- public boolean equals(Object another):将此字符串与指定对象进行比较,如果两者内容相同,则返回 true。
- public boolean equalsIgnoreCase(String another):将此字符串与另一个字符串进行比较,忽略大小写,如果两者内容相同,则返回 true。
测试字符串比较1.java
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//真
System.out.println(s1.equals(s3));//真
System.out.println(s1.equals(s4));//假
}
}
输出:
true
true
false
在上面的代码中,使用String类的equals()方法比较两个字符串。结果打印为布尔值,true或false。
测试字符串比较2.java
class Teststringcomparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2));//假
System.out.println(s1.equalsIgnoreCase(s2));//真
}
}
输出:
false
true
在上面的程序中,使用了String类的方法。如果 String 对象匹配并且两个字符串大小写相同,则 equals() 方法返回true 。无论字符串大小写如何,equalsIgnoreCase()都会返回 true。
2) 通过使用 == 运算符
== 运算符比较引用而不是值。
测试字符串比较3.java
class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true(因为两者都引用同一个实例)
System.out.println(s1==s3);//false(因为 s3 指的是在非池中创建的实例)
}
}
输出:
true
false
3)通过compareTo()方法比较字符串
上面的代码演示了使用==运算符来比较两个*String*对象。
4) 通过使用 compareTo() 方法
String 类的 compareTo() 方法按字典顺序比较值并返回一个整数值,该整数值描述第一个字符串是小于、等于还是大于第二个字符串。
假设 s1 和 s2 是两个 String 对象。如果:
- s1 == s2:该方法返回 0。
- s1 > s2:该方法返回一个正值。
- s1 < s2:该方法返回一个负值。
测试字符串比较4.java
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(因为 s1>s3)
System.out.println(s3.compareTo(s1));//-1(因为 s3 < s1 )
}
}
输出:
0
1
-1