Java函数:如何查找字符串中是否包含子串?
发布时间:2023-06-18 17:47:33
在Java中,提供了多种方法来判断字符串中是否包含子串。下面详细介绍3种常见的方法。
1. indexOf()方法
String类的indexOf()方法可以返回指定子串在原字符串中第一次出现的索引位置,若未出现则返回-1。
示例:
public class Test {
public static void main(String[] args) {
String str1 = "hello world";
String str2 = "world";
if (str1.indexOf(str2) != -1) {
System.out.println("包含子串");
} else {
System.out.println("不包含子串");
}
}
}
运行结果为:
包含子串
2. contains()方法
String类的contains()方法也可以用来判断字符串中是否包含指定的子串,方法返回一个boolean值。
示例:
public class Test {
public static void main(String[] args) {
String str1 = "hello world";
String str2 = "world";
if (str1.contains(str2)) {
System.out.println("包含子串");
} else {
System.out.println("不包含子串");
}
}
}
运行结果为:
包含子串
3. matches()方法
String类的matches()方法可以使用正则表达式来判断字符串中是否包含指定的子串。如果字符串中包含指定的子串,则方法返回true。
示例:
public class Test {
public static void main(String[] args) {
String str1 = "hello world";
String str2 = "world";
if (str1.matches(".*" + str2 + ".*")) {
System.out.println("包含子串");
} else {
System.out.println("不包含子串");
}
}
}
运行结果为:
包含子串
以上3种方法都可以实现字符串中是否包含子串的判断,选择哪种方法取决于你的具体需求。
需要注意的是,如果在一个大字符串中多次查找指定的子串,建议使用indexOf()方法,因为contains()方法在查找过程中会对字符串进行匹配操作,效率比indexOf()方法低;matches()方法虽然可以使用正则表达式,但对于较长的字符串,匹配操作的效率很低。
