Java教程

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

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

在这个例子中,我们将学习使用 Java 中的 contains() 和 indexOf() 方法检查字符串是否包含子字符串。
要理解此示例,您应该了解以下Java 编程主题:
Java 字符串 Java String substring()

示例 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() 方法来找到位置 txt 中的字符串 str1str2 。如果找到字符串,则返回字符串的位置。否则,返回 -1。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4