Program Java na kontrolu, či reťazec obsahuje podreťazec

V tomto príklade sa naučíme skontrolovať, či reťazec obsahuje podreťazec, pomocou metód contains () a indexOf () v Jave.

Aby ste pochopili tento príklad, mali by ste mať znalosti nasledujúcich tém programovania v jazyku Java:

  • Java String
  • Podreťazec Java String ()

Príklad 1: Skontrolujte, či reťazec obsahuje podreťazec pomocou 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ýkon

V reťazci je programiz. Programovanie nie je v reťazci prítomné.

Vo vyššie uvedenom príklade máme tri reťazce txt, str1 a str2. Tu sme použili metódu String contains () na kontrolu, či sú v txt prítomné reťazce str1 a str2.

Príklad 2: Skontrolujte, či reťazec obsahuje podreťazec pomocou 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ýkon

V reťazci je programiz. Programovanie nie je v reťazci prítomné.

V tomto príklade sme na nájdenie polohy reťazcov str1 a str2 v txt použili metódu String indexOf (). Ak je reťazec nájdený, jeho pozícia sa vráti. V opačnom prípade sa vráti -1 .

Zaujímavé články...