Java 子字串比較
給定一個字串及其長度為 k 的子字串,編寫一個 Java 程式來比較並查詢這些子字串是否相等。子字串是來自較長字串的一小部分字元。在 Java 中,String 是一個表示連續字元塊的類。
使用 compareTo() 方法
compareTo() 方法屬於 String 類,該類位於 java.lang 包中。它根據字串中包含的每個字元的 Unicode 值來比較兩個字串。如果指定的字串相等,則返回 0。
示例
在此示例中,我們使用 compareTo() 方法來比較子字串。
public class StringDemo {
public static void main(String[] args) {
String str1 = "tutorials point";
String str2 = str1.substring(10);
int result = str1.compareTo(str2);
// prints the return value of the comparison
if (result < 0) {
System.out.println("str1 is greater than str2");
}else if (result == 0) {
System.out.println("str1 is equal to str2");
}else {
System.out.println("str1 is less than str2");
}
}
}
執行程式碼後,將顯示以下結果:
str1 is less than str2
使用 equals() 方法
equals() 方法也屬於String類,該類位於java.lang包中。它也比較兩個字串,但如果字串例項包含相同順序的相同字元,則返回TRUE,否則返回FALSE。
示例
以下示例演示瞭如何使用 equals() 方法比較子字串。
public class CompareSubstring {
public static void main(String[] args) {
String str1 = "tutorials point";
String str2 = "point";
String substr = str1.substring(10);
boolean result = substr.equals(str2);
if (result) {
System.out.println("str1 is equal to str2");
} else {
System.out.println("str1 is not equal to str2");
}
}
}
執行此程式碼後,將產生以下結果:
str1 is equal to str2
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP