Java程式檢查給定字串中是否存在子字串
假設您有兩個字串,您的任務是編寫一個 Java 程式來檢查第二個字串是否為第一個字串的子字串。Java 中的字串是字元的不可變序列,子字串是其一小部分。
示例場景:−
Input 1: str = "The sunset is beautiful"; Input 2: sub_str = "sunset"; Output: res = found!!
使用迭代
在這種方法中,思路是使用巢狀 for 迴圈和 if 塊。外部 for 迴圈將迭代主字串的字元。對於每個起始位置 i,內部 for 迴圈將使用 if 塊將子字串的每個字元與主字串中相應的字元進行比較。
如果任何字元不匹配,內部迴圈將中斷,外部迴圈將移動到下一個起始位置。如果內部迴圈在不中斷的情況下完成,則表示在當前起始位置 i 找到子字串。然後程式碼列印索引。
示例
一個 Java 程式演示瞭如何檢查給定字串中是否存在子字串,如下所示:
public class Example {
public static void main(String args[]) {
String str = "Apples are red";
String substr = "are";
int n1 = str.length();
int n2 = substr.length();
System.out.println("String: " + str);
System.out.println("Substring: " + substr);
for (int i = 0; i <= n1 - n2; i++) {
int j;
for (j = 0; j < n2; j++) {
if (str.charAt(i + j) != substr.charAt(j))
break;
}
if (j == n2) {
System.out.println("The substring is present in the string at index " + i);
return;
}
}
System.out.println("The substring is not present in the string");
}
}
以上程式碼將顯示以下輸出:
String: Apples are red Substring: are The substring is present in the string at index 7
使用 contains() 方法
String 類 java.lang 包提供了 contains() 方法,該方法用於檢查特定字元序列是否存在於字串中。
示例
讓我們看看實際實現。
public class Example {
public static void main(String[] args) {
String str = "Apples are red";
String substr = "red";
// to check substring
boolean checkSubStr = str.contains(substr);
if (checkSubStr) {
System.out.println(substr + " is present in the string");
} else {
System.out.println(substr + " is not present in the string");
}
}
}
執行後,此程式碼將給出以下結果:
red is present in the string
使用 indexOf() 方法
這是另一種找出字串是否包含某個子字串的方法。在這裡,我們使用 String 類的 indexOf() 方法。它返回指定子字串第一次出現的索引。如果子字串不存在,則返回 -1。
示例
在這個 Java 程式中,我們使用 indexOf() 方法來檢查給定字串中是否存在子字串。
public class Example {
public static void main(String[] args) {
String str = "Apples are red";
String substr = "ples";
// to check substring
int checkSubStr = str.indexOf(substr);
if (checkSubStr != -1) {
System.out.println(substr + " is present in the string at index: " + checkSubStr);
} else {
System.out.println(substr + " is not present in the string");
}
}
}
以上程式碼的輸出如下:
ples is present in the string at index: 2
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP