V tem primeru se bomo naučili preveriti, ali niz vsebuje podniz, z uporabo metode Java () in () in indexOf ().
Če želite razumeti ta primer, morate poznati naslednje programske teme Java:
- Java Java
- Podniz niza Java ()
Primer 1: Preverite, ali niz vsebuje podniz, z uporabo vsebuje ()
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."); ) ) )
Izhod
Programiz je prisoten v nizu. Programiranje ni v nizu.
V zgornjem primeru imamo tri nize txt, str1 in str2. Tu smo uporabili metodo String contains (), da preverimo, ali sta niza str1 in str2 prisotna v txt.
Primer 2: Preverite, ali niz vsebuje podniz z uporabo 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."); ) ) )
Izhod
Programiz je prisoten v nizu. Programiranje ni v nizu.
V tem primeru smo z metodo String indexOf () našli položaj nizov str1 in str2 v txt. Če je niz najden, se vrne položaj niza. V nasprotnem primeru se vrne -1 .