我们如何检查字符串在Java中是否包含子字符串(忽略大小写)?
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.
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语