我们如何检查字符串在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.
热门推荐
1 泰迪狗狗如何训练
3 狗狗训练图
5 狗狗训练方法
6 训练狗狗不咬人
8 敏捷训练狗狗
10 训练狗狗吃饭
11 泰迪狗狗训练
12 狗狗从多大开始训练
13 狗狗训练学校费用
14 怎么去训练狗狗
15 狗狗训练狗狗
16 狗狗训练教程
17 训练狗狗装死
18 泰迪狗狗的训练方法