Apache commons库的org.apache.commons.lang3包的StringUtils类提供了一个名为containsIgnoreCase()的方法。
此方法接受两个分别代表源字符串和搜索字符串的String值,并验证源字符串是否包含忽略大小写的搜索字符串。它返回一个布尔值-
如果源字符串包含搜索字符串,则为true。
如果源字符串不包含搜索字符串,则为false。
查找字符串是否包含特定的子字符串,而不管大小写如何-
将以下依赖项添加到pom.xml文件中
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency>
获取源字符串。
获取搜索字符串。
containsIgnoreCase()通过将两个以上的字符串对象作为参数传递(以相同顺序)来调用该方法。
假设我们在D目录中有一个名为sample.txt的文件,其内容如下:
nhooo.com originated from the idea that there exists a class of readers who respond better to on-line content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. At nhooo.com we provide high quality learning-aids for free of cost.
以下Java示例从用户读取一个子字符串,并验证文件是否包含给定的子字符串,无论大小写如何。
import java.io.File;
import java.util.Scanner;
import org.apache.commons.lang3.StringUtils;
public class ContainsIgnoreCaseExample {
public static String fileToString(String filePath) throws Exception {
String input = null;
Scanner sc = new Scanner(new File(filePath));
StringBuffer sb = new StringBuffer();
while (sc.hasNextLine()) {
input = sc.nextLine();
sb.append(input);
}
return sb.toString();
}
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sub string to be verified: ");
String subString = sc.next();
String fileContents = fileToString("D:\\sample.txt");
//验证文件是否包含给定的子字符串
boolean result = StringUtils.containsIgnoreCase(fileContents, subString);
if(result) {
System.out.println("文件包含给定的子字符串。");
}else {
System.out.println("文件不包含给定的子字符串。");
}
}
}输出结果
Enter the sub string to be verified: comforts of their drawing rooms. 文件包含给定的子字符串。