Java 字串比較示例程式碼
我們可以透過 compareTo() 方法和 == 運算子比較 Java 中的字串。
compareTo() 方法: 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
廣告