Програма Java за проверка дали низът съдържа подниз

В този пример ще се научим да проверяваме дали низ съдържа подниз, използвайки метода contains () и indexOf () в Java.

За да разберете този пример, трябва да имате познанията по следните теми за програмиране на Java:

  • Java String
  • Подниз низ Java ()

Пример 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 (), за да проверим дали низовете str1 и str2 присъстват в txt.

Пример 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 .

Интересни статии...