Program Java ke kontrole, zda řetězec obsahuje podřetězec

V tomto příkladu se naučíme kontrolovat, zda řetězec obsahuje podřetězec pomocí metody contains () a indexOf () v Javě.

Abychom porozuměli tomuto příkladu, měli byste znát následující programovací témata Java:

  • Řetězec Java
  • Podřetězec Java String ()

Příklad 1: Zkontrolujte, zda řetězec obsahuje podřetězec pomocí 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."); ) ) )

Výstup

Programiz je přítomen v řetězci. Programování není v řetězci přítomno.

Ve výše uvedeném příkladu máme tři řetězce txt, str1 a str2. Zde jsme použili metodu String contains () ke kontrole, zda jsou v txt přítomny řetězce str1 a str2.

Příklad 2: Zkontrolujte, zda řetězec obsahuje podřetězec pomocí 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."); ) ) )

Výstup

Programiz je přítomen v řetězci. Programování není v řetězci přítomno.

V tomto příkladu jsme použili metodu String indexOf () k nalezení polohy řetězců str1 a str2 v txt. Pokud je řetězec nalezen, je vrácena poloha řetězce. Jinak se vrátí -1 .

Zajímavé články...