Java-programma om te controleren of een string een substring bevat

In dit voorbeeld zullen we leren controleren of een string een substring bevat met de methode contains () en indexOf () in Java.

Om dit voorbeeld te begrijpen, moet u kennis hebben van de volgende Java-programmeeronderwerpen:

  • Java-tekenreeks
  • Java String-substring ()

Voorbeeld 1: Controleer of een string een subtekenreeks bevat met 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."); ) ) )

Uitvoer

Programiz is aanwezig in de string. Programmering is niet aanwezig in de string.

In het bovenstaande voorbeeld hebben we drie string txt, str1 en str2. Hier hebben we de String contains () methode gebruikt om te controleren of strings str1 en str2 aanwezig zijn in txt.

Voorbeeld 2: controleer of een string een substring bevat met 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."); ) ) )

Uitvoer

Programiz is aanwezig in de string. Programmering is niet aanwezig in de string.

In dit voorbeeld hebben we de String indexOf () methode gebruikt om de positie van de strings str1 en str2 in txt te vinden. Als de string wordt gevonden, wordt de positie van de string geretourneerd. Anders wordt -1 geretourneerd.

Interessante artikelen...