У цьому прикладі ми навчимося перевіряти, чи містить рядок підстроку за допомогою методів contains () та indexOf () у Java.
Щоб зрозуміти цей приклад, ви повинні знати такі теми програмування Java:
- Рядок Java
- Підрядок Java String ()
Приклад 1: Перевірте, чи містить рядок підрядок, використовуючи contains ()
class Main ( public static void main(String() args) ( // create a string String txt = "This is Programiz"; String str1 = "Programiz"; String str2 = "Programming"; // check if name is present in txt // using contains() boolean result = txt.contains(str1); if(result) ( System.out.println(str1 + " is present in the string."); ) else ( System.out.println(str1 + " is not present in the string."); ) result = txt.contains(str2); if(result) ( System.out.println(str2 + " is present in the string."); ) else ( System.out.println(str2 + " is not present in the string."); ) ) )
Вихідні дані
Programiz присутній у рядку. Програмування у рядку відсутнє.
У наведеному вище прикладі ми маємо три рядки txt, str1 і str2. Тут ми використали метод String contains (), щоб перевірити, чи є в txt рядки str1 та str2.
Приклад 2: Перевірте, чи містить рядок підрядок, використовуючи indexOf ()
class Main ( public static void main(String() args) ( // create a string String txt = "This is Programiz"; String str1 = "Programiz"; String str2 = "Programming"; // check if str1 is present in txt // using indexOf() int result = txt.indexOf(str1); if(result == -1) ( System.out.println(str1 + " not is present in the string."); ) else ( System.out.println(str1 + " is present in the string."); ) // check if str2 is present in txt // using indexOf() result = txt.indexOf(str2); if(result == -1) ( System.out.println(str2 + " is not present in the string."); ) else ( System.out.println(str2 + " is present in the string."); ) ) )
Вихідні дані
Programiz присутній у рядку. Програмування у рядку відсутнє.
У цьому прикладі ми використали метод String indexOf (), щоб знайти позицію рядків str1 та str2 у txt. Якщо рядок знайдено, повертається позиція рядка. В іншому випадку повертається -1 .