Java函数如何检查字符串是否包含特定的子字符串?
发布时间:2023-07-01 10:20:14
Java中有多种方式可以检查一个字符串是否包含特定的子字符串。下面是其中一些常用的方法:
1. 使用indexOf()方法:String类提供了indexOf()方法来检查一个字符串是否包含另一个字符串。该方法返回子字符串在原字符串中 次出现的索引,如果不存在则返回-1。通过判断返回值是否为-1,可以确定是否包含该子字符串。例如:
String str = "Hello World";
String subStr = "Hello";
if (str.indexOf(subStr) != -1) {
System.out.println("包含子字符串");
} else {
System.out.println("不包含子字符串");
}
2. 使用contains()方法:String类还提供了contains()方法来判断一个字符串是否包含另一个字符串。该方法返回一个boolean值,如果包含则返回true,否则返回false。例如:
String str = "Hello World";
String subStr = "Hello";
if (str.contains(subStr)) {
System.out.println("包含子字符串");
} else {
System.out.println("不包含子字符串");
}
3. 使用matches()方法:String类还提供了matches()方法来通过正则表达式匹配字符串。可以使用该方法来判断一个字符串是否包含特定的子字符串。例如:
String str = "Hello World";
String pattern = ".*Hello.*";
if (str.matches(pattern)) {
System.out.println("包含子字符串");
} else {
System.out.println("不包含子字符串");
}
4. 使用contains方法和正则表达式:通过将子字符串包装成正则表达式,然后使用contains方法来判断是否匹配。例如:
String str = "Hello World";
String subStr = "Hello";
if (str.contains(".*" + subStr + ".*")) {
System.out.println("包含子字符串");
} else {
System.out.println("不包含子字符串");
}
以上就是几种常用的方法来检查一个字符串是否包含特定子字符串的方式。根据具体的需求和场景选择适合的方法来使用。
