Programma Java per verificare se una stringa contiene una sottostringa

In questo esempio, impareremo a controllare se una stringa contiene una sottostringa utilizzando il metodo contains () e indexOf () in Java.

Per comprendere questo esempio, è necessario conoscere i seguenti argomenti di programmazione Java:

  • Java String
  • Sottostringa Java String ()

Esempio 1: controlla se una stringa contiene una sottostringa utilizzando 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."); ) ) )

Produzione

Programiz è presente nella stringa. La programmazione non è presente nella stringa.

Nell'esempio precedente, abbiamo tre stringhe txt, str1 e str2. Qui, abbiamo utilizzato il metodo String contains () per verificare se le stringhe str1 e str2 sono presenti in txt.

Esempio 2: controlla se una stringa contiene una sottostringa utilizzando 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."); ) ) )

Produzione

Programiz è presente nella stringa. La programmazione non è presente nella stringa.

In questo esempio, abbiamo utilizzato il metodo String indexOf () per trovare la posizione delle stringhe str1 e str2 in txt. Se la stringa viene trovata, viene restituita la posizione della stringa. In caso contrario, viene restituito -1 .

Articoli interessanti...