String类的contains()方法接受Sting值作为参数,验证当前String对象是否包含指定的String,如果存在则返回true(否则返回false)。
String类的toLoweCase()方法将当前String中的所有字符转换为小写并返回。
查找字符串是否包含特定的子字符串,而不管大小写如何-获取字符串。
获取子字符串。
使用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.