Neste exemplo, aprenderemos a verificar se uma string contém uma substring usando os métodos contains () e indexOf () em Java.
Para entender este exemplo, você deve ter conhecimento dos seguintes tópicos de programação Java:
- Java String
- Substring Java String ()
Exemplo 1: verifique se uma string contém uma substring usando 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."); ) ) )
Resultado
Programiz está presente na string. A programação não está presente na string.
No exemplo acima, temos três strings txt, str1 e str2. Aqui, usamos o método String contains () para verificar se as strings str1 e str2 estão presentes em txt.
Exemplo 2: verifique se uma string contém uma substring usando 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."); ) ) )
Resultado
Programiz está presente na string. A programação não está presente na string.
Neste exemplo, usamos o método String indexOf () para encontrar a posição das strings str1 e str2 em txt. Se a string for encontrada, a posição da string é retornada. Caso contrário, -1 é retornado.