在 Java 中检查字符串是否包含不区分大小写的子串
Mohammad Irfan
2023年10月12日
Java
Java String
- 在 Java 中的字符串中查找不区分大小写的子字符串
-
在 Java 中使用
StringUtils在字符串中查找不区分大小写的子字符串 -
在 Java 中使用
contains()方法查找字符串中不区分大小写的子字符串 -
在 Java 中使用
matches()方法查找字符串中不区分大小写的子字符串
本教程介绍如何在 Java 中检查或查找字符串是否包含子字符串。
String 是一个字符序列,有时也称为字符数组。在 Java 中,String 是一个处理所有与字符串相关的操作并提供实用方法的类。
本文演示如何在字符串中查找子字符串。
子字符串是字符串的一部分,也是字符串。它可以有一个或多个字符。
不区分大小写的字符串是不关心字母的小写或大写的字符串。让我们通过一些例子来理解。
在 Java 中的字符串中查找不区分大小写的子字符串
在这个例子中,我们使用了 Pattern 类及其 compile()、matcher() 和 find() 方法来检查字符串是否包含子字符串。我们使用了 CASE_INSENSITIVE,它返回一个布尔值,true 或 false。
请参见下面的示例。
import java.util.regex.Pattern;
public class SimpleTesting {
public static void main(String[] args) {
String str = "DelftStack";
String strToFind = "St";
System.out.println(str);
boolean ispresent =
Pattern.compile(Pattern.quote(strToFind), Pattern.CASE_INSENSITIVE).matcher(str).find();
if (ispresent)
System.out.println("String is present");
else
System.out.println("String not found");
}
}
输出:
DelftStack
String is present
在 Java 中使用 StringUtils 在字符串中查找不区分大小写的子字符串
使用 Apache 公共库,你可以使用 StringUtils 类及其 containsIgnoreCase() 方法来查找子字符串。请参见下面的示例。
你必须将 Apache 公共 JAR 添加到你的项目中才能执行此代码。
import org.apache.commons.lang3.StringUtils;
public class SimpleTesting {
public static void main(String[] args) {
String str = "DelftStack";
String strToFind = "St";
System.out.println(str);
boolean ispresent = StringUtils.containsIgnoreCase(str, strToFind);
if (ispresent)
System.out.println("String is present");
else
System.out.println("String not found");
}
}
输出:
DelftStack
String is present
在 Java 中使用 contains() 方法查找字符串中不区分大小写的子字符串
在这个例子中,我们使用了 String 类的 contains() 方法,如果子字符串存在则返回 true。我们使用 toLowerCase() 首先将所有字符转换为小写,然后传递给 contains() 方法。
请参见下面的示例。
public class SimpleTesting {
public static void main(String[] args) {
String str = "DelftStack";
String strToFind = "St";
System.out.println(str);
boolean ispresent = str.toLowerCase().contains(strToFind.toLowerCase());
if (ispresent)
System.out.println("String is present");
else
System.out.println("String not found");
}
}
输出:
DelftStack
String is present
在 Java 中使用 matches() 方法查找字符串中不区分大小写的子字符串
在这个例子中,我们使用了 String 类的 matches() 方法,如果子字符串存在则返回 true。它将正则表达式作为参数。
请参见下面的示例。
public class SimpleTesting {
public static void main(String[] args) {
String str = "DelftStack";
String strToFind = "St";
System.out.println(str);
boolean ispresent = str.matches("(?i).*" + strToFind + ".*");
if (ispresent)
System.out.println("String is present");
else
System.out.println("String not found");
}
}
输出:
DelftStack
String is present
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe