📌  相关文章
📜  Java程序检查字符串包含子字符串

📅  最后修改于: 2020-09-26 17:58:02             🧑  作者: Mango

在此示例中,我们将学习使用Java中的contains()和indexOf()方法来检查字符串包含子字符串。

示例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()方法来检查txt中是否存在字符串 str1str2


示例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()方法来找到字符串 str1str2txt中的位置 。如果找到字符串返回字符串的位置。否则,返回-1