跳到主要内容

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

要理解这个示例,你需要了解以下 Java 编程 主题:

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

class Main {
public static void main(String[] args) {
// 创建一个字符串
String txt = "This is Programiz";
String str1 = "Programiz";
String str2 = "Programming";

// 使用 contains() 检查 txt 是否包含 str1
boolean result = txt.contains(str1);
if(result) {
System.out.println(str1 + " 存在于字符串中。");
}
else {
System.out.println(str1 + " 不存在于字符串中。");
}

// 检查 txt 是否包含 str2
result = txt.contains(str2);
if(result) {
System.out.println(str2 + " 存在于字符串中。");
}
else {
System.out.println(str2 + " 不存在于字符串中。");
}
}
}

输出

Programiz 存在于字符串中。
Programming 不存在于字符串中。

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

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

class Main {
public static void main(String[] args) {
// 创建一个字符串
String txt = "This is Programiz";
String str1 = "Programiz";
String str2 = "Programming";

// 使用 indexOf() 检查 txt 是否包含 str1
int result = txt.indexOf(str1);
if(result == -1) {
System.out.println(str1 + " 不存在于字符串中。");
}
else {
System.out.println(str1 + " 存在于字符串中。");
}

// 检查 txt 是否包含 str2
result = txt.indexOf(str2);
if(result == -1) {
System.out.println(str2 + " 不存在于字符串中。");
}
else {
System.out.println(str2 + " 存在于字符串中。");
}
}
}

输出

Programiz 存在于字符串中。
Programming 不存在于字符串中。

在这个示例中,我们使用了 String indexOf() 方法来找出字符串 str1str2txt 中的位置。如果找到字符串,将返回字符串的位置。否则,返回 -1