在 Java 中,如何检查字符串是否包含子字符串(忽略大小写)?

javaobject oriented programmingprogramming更新于 2024/2/14 7:40:17

String 类的 contains() 方法接受 Sting 值作为参数,验证当前 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");
      //将文件内容转换为小写
      fileContents = fileContents.toLowerCase();
      //将子字符串转换为小写
      subString = subString.toLowerCase();
      //验证文件是否包含给定的子字符串
      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.

相关文章


有用资源