如何在Java中检查字符串是否包含子字符串(忽略大小写)?
String类的**contains()**方法接受String值作为参数,验证当前String对象是否包含指定的String,如果包含则返回true(否则返回false)。
String类的**toLowerCase()**方法将当前字符串中的所有字符转换为小写并返回。
要查找字符串是否包含特定子字符串(不区分大小写) -
获取字符串。
获取子字符串。
使用toLowerCase()方法将字符串值转换为小写字母,将其存储为fileContents。
使用toLowerCase()方法将字符串值转换为小写字母,将其存储为subString。
通过将subString作为参数传递给它,在fileContents上调用**contains()**方法。
示例
假设我们在D目录中有一个名为sample.txt的文件,其内容如下:
Tutorials point 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 Tutorials point we provide high quality learning-aids for free of cost.
下面的Java示例从用户读取子字符串,并验证文件是否包含给定的子字符串(不区分大小写)。
import java.io.File;
import java.util.Scanner;
public class SubStringExample {
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");
//Converting the contents of the file to lower case
fileContents = fileContents.toLowerCase();
//Converting the sub string to lower case
subString = subString.toLowerCase();
//Verify whether the file contains the given sub String
boolean result = fileContents.contains(subString);
if(result) {
System.out.println("File contains the given sub string.");
} else {
System.out.println("File doesnot contain the given sub string.");
}
}
}输出
Enter the sub string to be verified: comforts of their drawing rooms. File contains the given sub string.
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP