Java 字串對比方法。


Java 字串類提供了不同的比較方法,即

compareTo() 方法

此方法按字典順序比較兩個字串。此方法返回  如果當前字串物件在字典順序上位於引數字串之前,則返回一個負整數。 如果當前字串物件在字典順序上位於引數之後,則返回一個正整數。 如果字串相等,則返回 true。

示例

import java.lang.*;
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "tutorials", str2 = "point";
      // comparing str1 and str2
      int retval = str1.compareTo(str2);
      // prints the return value of the comparison
      if (retval < 0) {
         System.out.println("str1 is greater than str2");
      }
      else if (retval == 0) {
         System.out.println("str1 is equal to str2");
      } else {
         System.out.println("str1 is less than str2");
      }
   }
}

輸出

str1 is less than str2


compareToIgnoreCase() 方法

此方法與 compareTo() 方法相同,按字典順序比較兩個字串,忽略大小寫差異。

示例

import java.lang.*;
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "tutorials", str2 = "TUTORIALS";
     
      // comparing str1 and str2 with case ignored
      int retval = str1.compareToIgnoreCase(str2);
     
      // prints the return value of the comparison
      if (retval > 0) {
         System.out.println("str1 is greater than str2");
     }
     else if (retval == 0) {
         System.out.println("str1 is equal to str2");
      } else {
         System.out.println("str1 is less than str2");
      }
   }
}

輸出

str1 is equal to str2

equals() 方法

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

示例

import java.lang.*;
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "sachin tendulkar";
      String str2 = "amrood admin";
      String str3 = "amrood admin";
     
      // checking for equality
      boolean retval1 = str2.equals(str1);
      boolean retval2 = str2.equals(str3);
     
      // prints the return value
      System.out.println("str2 is equal to str1 = " + retval1);
      System.out.println("str2 is equal to str3 = " + retval2);
   }
}

輸出

str2 is equal to str1 = false
str2 is equal to str3 = true


equalsIgnoreCase() 方法 

此方法等於 ignoreCase() 方法,除了以下情況:如果兩個字串的長度相同且兩個字串中對應的字元在忽略大小寫的情況下相等,則認為這兩個字串相等。

示例

import java.lang.*;
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "sachin tendulkar";
      String str2 = "amrood admin";
      String str3 = "AMROOD ADMIN";
     
      // checking for equality with case ignored
      boolean retval1 = str2.equalsIgnoreCase(str1);
      boolean retval2 = str2.equalsIgnoreCase(str3);
     
      // prints the return value
      System.out.println("str2 is equal to str1 = " + retval1);
      System.out.println("str2 is equal to str3 = " + retval2);
   }
}

輸出

str2 is equal to str1 = false
str2 is equal to str3 = true

更新於: 2020-02-26

504 次瀏覽

開啟你的 職業 生涯

完成課程後獲取認證

開始
廣告
© . All rights reserved.