java 忽略大小写查找子串_我们如何检查字符串在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个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值