U ovom ćemo primjeru naučiti provjeravati sadrži li niz podniz koristeći metodu contains () i indexOf () u Javi.
Da biste razumjeli ovaj primjer, trebali biste imati znanje o sljedećim temama programiranja Java:
- Java String
- Podniz Java String ()
Primjer 1: Provjerite sadrži li niz podstring pomoću 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."); ) ) )
Izlaz
Programiz je prisutan u nizu. Programiranje nije prisutno u nizu.
U gornjem primjeru imamo tri niza txt, str1 i str2. Ovdje smo koristili metodu String contains () kako bismo provjerili jesu li u txt prisutni nizovi str1 i str2.
Primjer 2: Provjerite sadrži li niz podniz koristeći 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."); ) ) )
Izlaz
Programiz je prisutan u nizu. Programiranje nije prisutno u nizu.
U ovom smo primjeru koristili metodu String indexOf () za pronalaženje položaja nizova str1 i str2 u txt-u. Ako se niz pronađe, vraća se položaj niza. U suprotnom se vraća -1 .