Java 中检查字符串是否包含忽略大小写的子字符串的方法

javaobject oriented programmingprogramming更新于 2024/2/14 10:52:17

Apache commons 库的 org.apache.commons.lang3 包的 StringUtils 类提供了一个名为 containsIgnoreCase() 的方法。

此方法接受两个分别代表源字符串和搜索字符串的 String 值,验证源字符串是否包含忽略大小写的搜索字符串。它返回一个布尔值,即 −

  • 如果源字符串包含搜索字符串,则为 true。

  • 如果源字符串不包含搜索字符串,则为 false。

要查找字符串是否包含特定子字符串(无论大小写如何),则 −

  • 将以下依赖项添加到 pom.xml 文件

<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-lang3</artifactId>
   <version>3.9</version>
</dependency>
  • 获取源字符串。

  • 获取搜索字符串。

  • 通过将上述两个字符串对象作为参数(以相同的顺序)传递来调用 containsIgnoreCase() 方法。

示例

假设我们在 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;
import org.apache.commons.lang3.StringUtils;
public class ContainsIgnoreCaseExample {
   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("输入要验证的子字符串:");
      String subString = sc.next();
      String fileContents = fileToString("D:\sample.txt");
      //验证文件是否包含给定的子字符串
      boolean result = StringUtils.containsIgnoreCase(fileContents, subString);
      if(result) {
         System.out.println("文件包含给定的子字符串。");
      }else {
           System.out.println("文件不包含给定的子字符串。");
      }
   }
}

输出

输入要验证的子字符串:
comforts of their drawing rooms.
文件包含给定的子字符串。

相关文章


有用资源