Java 字串比較方法。


Java String 類提供了不同的比較方法,包括

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 年 2 月 26 日

504 次瀏覽

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.