如何在Java中檢查字串是否包含子字串(忽略大小寫)?


String類的**contains()**方法接受String值作為引數,驗證當前String物件是否包含指定的String,如果包含則返回true(否則返回false)。

String類的**toLowerCase()**方法將當前字串中的所有字元轉換為小寫並返回。

要查詢字串是否包含特定子字串(不區分大小寫) -

  • 獲取字串。

  • 獲取子字串。

  • 使用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.

更新於: 2019年10月11日

4K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告