У овом примеру научићемо да проверавамо да ли низ садржи подниз користећи методу цонтаинс () и индекОф () у Јави.
Да бисте разумели овај пример, требало би да имате знање о следећим темама програмирања Јава:
- Јава Стринг
- Јава стринг подниз ()
Пример 1: Проверите да ли низ садржи подниз користећи усинг ()
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."); ) ) )
Оутпут
Програмиз је присутан у низу. Програмирање није присутно у низу.
У горњем примеру имамо три низа ткт, стр1 и стр2. Овде смо користили методу Стринг цонтаинс () да бисмо проверили да ли су стрингови стр1 и стр2 присутни у ткт-у.
Пример 2: Проверите да ли низ садржи подниз користећи индекОф ()
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."); ) ) )
Оутпут
Програмиз је присутан у низу. Програмирање није присутно у низу.
У овом примеру користили смо методу Стринг индекОф () да бисмо пронашли положај низова стр1 и стр2 у ткт. Ако се низ пронађе, враћа се положај низа. У супротном се враћа -1 .