English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在此示例中,我们将学习使用Java中的contains()和indexOf()方法来检查字符串是否包含子字符串。
要理解此示例,您应该了解以下Java编程主题:
class Main { public static void main(String[] args) { //创建一个字符串 String txt = "This is w3codebox"; String str1 = "w3codebox"; String str2 = "Programming"; //检查txt中是否存在名称 //使用 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 未出现在字符串中.
在上面的实例中,我们有三个串txt,str1和str2。在这里,我们使用的 String的contains()方法来检查字符串str1和str2是否出现在txt中。
class Main { public static void main(String[] args) { //创建一个字符串 String txt = "This is w3codebox"; 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。