示例 1: 使用 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."); } } }
输出
Programiz is present in the string. Programming is not present in the string.
在上面的例子中,我们有三个字符串
txt、
str1 和
str2。在这里,我们使用了 String contains() 方法来检查字符串是否
str1 和
str2 出现在
txt 中。
示例 2: 使用 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."); } } }
输出
Programiz is present in the string. Programming is not present in the string.
在这个例子中,我们使用了 String indexOf() 方法来找到位置
txt 中的字符串
str1 和
str2 。如果找到字符串,则返回字符串的位置。否则,返回 -1。