Java函数如何判断一个字符串是否包含某个子串?
发布时间:2023-08-20 16:10:06
在Java中,我们可以使用String类的contains()方法来判断一个字符串是否包含某个子串。contains()方法返回一个布尔值,如果字符串包含指定的子串,返回true,否则返回false。
下面是使用contains()方法判断字符串是否包含子串的示例代码:
public class Main {
public static void main(String[] args) {
String str1 = "Hello, world!";
String str2 = "world";
if (str1.contains(str2)) {
System.out.println("str1 contains str2");
} else {
System.out.println("str1 does not contain str2");
}
}
}
输出结果为:
str1 contains str2
除了使用contains()方法,我们还可以使用其他方法来判断字符串是否包含子串,如startsWith()和endsWith()方法。startsWith()方法用于判断字符串是否以指定的子串开始,endsWith()方法用于判断字符串是否以指定的子串结束。两个方法也返回布尔值,如果字符串满足条件,返回true,否则返回false。
下面是使用startsWith()和endsWith()方法判断字符串是否包含子串的示例代码:
public class Main {
public static void main(String[] args) {
String str1 = "Hello, world!";
String str2 = "Hello";
String str3 = "world";
if (str1.startsWith(str2)) {
System.out.println("str1 starts with str2");
} else {
System.out.println("str1 does not start with str2");
}
if (str1.endsWith(str3)) {
System.out.println("str1 ends with str3");
} else {
System.out.println("str1 does not end with str3");
}
}
}
输出结果为:
str1 starts with str2 str1 does not end with str3
除了以上三个方法,我们还可以使用indexOf()方法和正则表达式来判断字符串是否包含子串。indexOf()方法返回子串在字符串中第一次出现的位置,如果未找到子串,返回-1,否则返回子串的起始位置。利用indexOf()方法,我们可以判断子串是否存在于字符串中。
以下是使用indexOf()方法判断字符串是否包含子串的示例代码:
public class Main {
public static void main(String[] args) {
String str1 = "Hello, world!";
String str2 = "world";
int index = str1.indexOf(str2);
if (index != -1) {
System.out.println("str1 contains str2");
} else {
System.out.println("str1 does not contain str2");
}
}
}
输出结果为:
str1 contains str2
正则表达式也是一种判断字符串是否包含子串的方法。我们可以使用String类的matches()方法来判断字符串是否匹配指定的正则表达式。正则表达式可以更灵活地匹配字符串,但是相比其他方法,它的执行效率较低。
下面是使用matches()方法判断字符串是否包含子串的示例代码:
public class Main {
public static void main(String[] args) {
String str1 = "Hello, world!";
String str2 = "world";
if (str1.matches(".*" + str2 + ".*")) {
System.out.println("str1 contains str2");
} else {
System.out.println("str1 does not contain str2");
}
}
}
输出结果为:
str1 contains str2
以上是关于Java中判断字符串是否包含某个子串的几种方法。根据实际情况,你可以选择合适的方法来判断字符串是否包含某个子串。
