Java 程序检查字符串是否包含子字符串

要理解此示例,您应该具备以下 Java 编程的知识:

示例 1:使用 contains() 检查字符串是否包含子字符串

public class Main {
  public static void main(String[] args) {
    // create a string
    String txt = "This is Program";
    String str1 = "Program";
    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.");
    }
  }
}

输出

Program is present in the string.
Programming is not present in the string.

在上面的例子中,我们有三个字符串 txt, str1, 和 str2. 在这里,我们使用了 String contains()方法来检查字符串是否字符串 str1str2 存在于 txt 中.

示例 2:使用 indexOf() 检查字符串是否包含子字符串

public class Main {
  public static void main(String[] args) {
    // create a string
    String txt = "This is Program";
    String str1 = "Program";
    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.");
    }
  }
}

输出

Program is present in the string.
Programming is not present in the string.

在这个例子中,我们使用了String indexOf()方法在 txt 中查找是否存在 str1str2. 如果找到字符串,则返回字符串的位置。否则,返回 -1