English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
En este ejemplo, aprenderemos a usar los métodos contains() y indexOf() de Java para verificar si una cadena contiene una subcadena.
Para entender este ejemplo, debe entender lo siguienteProgramación JavaTema:
class Main { public static void main(String[] args) { //Crear una cadena String txt = "This is w"3codebox"; String str1 = "w3codebox"; String str2 = "Programming"; //para verificar si existe el nombre en txt //Usar contains() boolean result = txt.contains(str1); if(result) { System.out.println(str1 + " 出现在字符串中."); } else { System.out.println(str1 + " 未出现在字符串中."); } result = txt.contains(str2); if(result) { System.out.println(str2 + " 出现在字符串中."); } else { System.out.println(str2 + " 未出现在字符串中."); } } }
输出结果
w3codebox 出现在字符串中. Programming 未出现在字符串中.
En el ejemplo anterior, tenemos tres cadenas txt, str1和str2。Aquí, estamos usando String decontains()Método para verificar la cadena str1和str2¿Aparece en txt?.
class Main { public static void main(String[] args) { //Crear una cadena String txt = "This is w"3codebox"; String str1 = "w3codebox"; String str2 = "Programming"; //检查str1是否存在于txt中 //使用 indexOf() int result = txt.indexOf(str1); if(result == -1) { System.out.println(str1 + " 未出现在字符串中."); } else { System.out.println(str1 + " 出现在字符串中."); } //检查str2是否存在于txt中 //使用 indexOf() result = txt.indexOf(str2); if(result == -1) { System.out.println(str2 + " 未出现在字符串中."); } else { System.out.println(str2 + " 出现在字符串中."); } } }
输出结果
w3codebox 出现在字符串中. Programming 未出现在字符串中.
在这个实例中,我们使用字符串的indexOf()方法来查找字符串str1和str2在txt中的位置。 如果找到字符串,则返回字符串的位置。 否则,返回-1。