Java 字串比較示例程式碼
我們可以使用 compareTo() 方法和 == 運算子來比較 Java 中的字串。
comapareTo() 方法: The compareTo() 方法按字母順序比較兩個字串。比較基於字串中每個字元的 Unicode 值。此 String 物件表示的字元序列按字母順序與引數字串表示的字元序列進行比較。
The == 運算子: 您可以使用 == 運算子比較兩個字串。但是,它比較的是給定變數的引用,而不是值。
示例
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); System.out.println(str1==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"); } } }
輸出
false str1 is less than str2
廣告