用 Java 比較兩個字串的字典順序。
String 類的 compareTo() 方法。此方法按字典順序比較兩個字串。比較基於字串中每個字元的 Unicode 值。由此 String 物件表示的字元序列將與由引數字串表示的字元序列進行字典順序比較。此方法返回
- 如果當前 String 物件在字典順序上位於引數字串之前,則返回負整數。
- 如果當前 String 物件在字典順序上位於引數字串之後,則返回正整數
- 如果字串相等,則返回 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
廣告