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

要理解此示例,您应了解以下Java编程主题


示例 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.

在上面的示例中,我们有三个字符串 txtstr1str2。在这里,我们使用了 String contains() 方法来检查 str1str2 是否存在于 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() 方法来查找 txtstr1str2 的位置。如果找到字符串,则返回字符串的位置。否则,返回 -1

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战