English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Neste exemplo, vamos aprender a usar os métodos contains() e indexOf() do Java para verificar se uma string contém uma substring.
Para entender este exemplo, você deve saber o seguinteProgramação JavaTema:
class Main { public static void main(String[] args) { //Criar uma string String txt = "This is w"3codebox"; String str1 = "w3codebox"; String str2 = "Programming"; //Para verificar se o nome existe em txt //Usar contains() boolean result = txt.contains(str1); if(result) { System.out.println(str1 + " appears in the string."); } else { System.out.println(str1 + " does not appear in the string."); } result = txt.contains(str2); if(result) { System.out.println(str2 + " appears in the string."); } else { System.out.println(str2 + " does not appear in the string."); } } }
Output Results
w3codebox appears in the string. Programming does not appear in the string.
No exemplo acima, temos três strings txt, str1and str2。Aqui, usamos o String decontains()Método para verificar se uma string str1and str2Se aparece em txt.
class Main { public static void main(String[] args) { //Criar uma string String txt = "This is w"3codebox"; String str1 = "w3codebox"; String str2 = "Programming"; //Check str1whether it exists in txt //using indexOf() int result = txt.indexOf(str1); if(result == -1) { System.out.println(str1 + " does not appear in the string."); } else { System.out.println(str1 + " appears in the string."); } //Check str2whether it exists in txt //using indexOf() result = txt.indexOf(str2); if(result == -1) { System.out.println(str2 + " does not appear in the string."); } else { System.out.println(str2 + " appears in the string."); } } }
Output Results
w3codebox appears in the string. Programming does not appear in the string.
In this example, we usethe indexOf() of the stringmethod to find the string str1and str2Position in txt. If the string is found, return the position of the string. Otherwise, return-1.