Java程式檢查字串是否包含子字串
在Java中,字串是一個類,它儲存一系列用雙引號括起來的字元,字串中連續的字元序列稱為子字串。這些字元實際上是String型別的物件。本文旨在編寫Java程式來檢查字串是否包含子字串。要檢查給定的字串是否包含子字串,我們可以使用indexOf()、contains()和substring()方法以及條件塊。
Java程式檢查字串是否包含子字串
我們將在Java程式中使用以下內建方法來檢查字串是否包含子字串:
indexOf()
contains()
substring()
讓我們逐一討論這些方法,但在討論之前,有必要用一個例子來理解問題陳述。
示例
輸入
String = "Simply Easy Learning"; Substring = "Easy";
輸出
The string contains the given substring
在上例中,子字串“Easy”包含在給定的字串“Simply Easy Learning”中。因此,我們得到輸出訊息“字串包含給定的子字串”。
現在,讓我們討論Java程式,以檢查字串是否包含給定的子字串。
使用indexOf()方法
String類的indexOf()方法用於查詢給定字串中指定子字串的位置。如果找到子字串,它返回該子字串的第一次出現索引;如果未找到,則返回-1。
語法
String.indexOf(subString);
示例
以下示例說明如何使用indexOf()方法檢查字串是否包含給定的子字串。
public class Example1 { public static void main(String []args) { String inputStr = "Simply Easy Learning"; // Substring to be checked String subStr = "Easy"; System.out.println("The given String: " + inputStr); System.out.println("The given Substring: " + subStr); // checking the index of substring int index = inputStr.indexOf(subStr); // to check string contains the substring or not if (index != -1) { System.out.println("The string contains the given substring"); } else { System.out.println("The string does not contain the given substring"); } } }
輸出
The given String: Simply Easy Learning The given Substring: Easy The string contains the given substring
使用contains()方法
contains()方法也是String類的內建方法,用於識別字符串是否包含給定的子字串。它的返回型別是布林值,這意味著如果子字串在字串中可用,則返回true,否則返回false。
示例
在這個例子中,我們將使用內建方法contains()來檢查字串是否包含給定的子字串。
public class Example2 { public static void main(String []args) { String inputStr = "Simply Easy Learning"; // Substring to be checked String subStr = "Simply"; System.out.println("The given String: " + inputStr); System.out.println("The given Substring: " + subStr); // to check string contains the substring or not if (inputStr.contains(subStr)) { System.out.println("The string contains the given substring"); } else { System.out.println("The string does not contain the given substring"); } } }
輸出
The given String: Simply Easy Learning The given Substring: Simply The string contains the given substring
使用substring()方法
這是String類的另一種方法,用於從給定字串中列印子字串。它接受起始和結束索引作為引數,並返回這兩個索引之間可用的字元。
示例
在下面的示例中,我們將使用substring()方法從給定字串的索引0到2查詢子字串。
public class Example3 { public static void main(String []args) { // initializing the string String inputStr = "Simply Easy Learning"; System.out.println("The given String is: " + inputStr); // Creating a Substring String subStr = inputStr.substring(0, 2); // printing one of the substring of the given string System.out.println("One substring of the given String: " + subStr); } }
輸出
The given String is: Simply Easy Learning One substring of the given String: Si
結論
在本文中,我們學習了什麼是字串和子字串,以及如何檢查字串是否包含給定的子字串。為了檢查給定的子字串是否在指定的字串中可用,我們使用了Java String類的內建方法indexOf()、contains()和substring()。