如何在 Java 中比較兩個字串



問題說明

如何比較兩個字串?

解決方案

以下示例透過使用字串類的 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() 比較字串

此方法將此字串與指定的物件進行比較。當且僅當引數不為 null 並且是一個表示與此物件相同的字元序列的字串物件時,結果為 true。

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 

透過 == 運算子比較字串

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.htm
廣告