如何在 Java 中比较两个字符串

Java 中,字符串比较对于匹配、排序和身份验证等任务非常重要。本教程介绍了比较字符串的不同方法。以下是根据内容或引用比较字符串的各种方法 -

  • 通过 compareTo() 方法比较字符串

  • 通过 equals() 方法比较字符串

  • 通过 == 运算符比较字符串

通过 compareTo() 方法比较字符串

compareTo() 方法 根据字典顺序比较两个字符串,使用每个字符的 Unicode 值。如果两个字符串相等,则返回 0;如果第一个字符串按字典顺序较小,则返回小于 0 的值;如果第一个字符串按字典顺序较大,则返回大于 0 的值。

示例

以下示例使用 string 类的 str compareTo (string)、str compareToIgnoreCase(String) 和 str compareTo(object string) 比较两个字符串,并返回比较字符串前奇数个字符的 ASCII 差异 -

public class StringCompareEmp{
   public static void main(String args[]){
      String str = "Hello World";
      String anotherString = "hello world";
      Object objStr = str;
      System.out.println( str.compareTo(anotherString) );
      System.out.println( str.compareToIgnoreCase(anotherString) );
      System.out.println( str.compareTo(objStr.toString()));
   }
}

输出

-32
0
0

通过 equals() 方法比较字符串

equals() 方法 将此字符串与指定对象进行比较。当且仅当参数不为空且为表示与此对象相同的字符序列的 String 对象时,结果才为 true。

示例

以下示例通过 equals() 方法比较字符串 −

public class StringCompareequl{
   public static void main(String []args){
      String s1 = "tutorialspoint";
      String s2 = "tutorialspoint";
      String s3 = new String ("Tutorials Point");
      System.out.println(s1.equals(s2));
      System.out.println(s2.equals(s3));
   }
}

输出

true 
false 

通过 == 运算符比较字符串

== 运算符通过内存引用而不是内容比较两个字符串。如果它们引用同一个对象,则返回 true,否则返回 false。

示例

以下示例使用 == 运算符比较字符串 -

public class StringCompareequl{
   public static void main(String []args){
      String s1 = "tutorialspoint";
      String s2 = "tutorialspoint";
      String s3 = new String ("Tutorials Point");
      System.out.println(s1 == s2);
      System.out.println(s2 == s3);
   }
}

输出

true
false 
java_strings.html