How do we check if a String contains a substring (ignoring case) in Java?


The contains() method of the String class accepts Sting value as a parameter, verifies whether the current String object contains the specified String and returns true if it does (else false).

The toLoweCase() method of the String class converts all the characters in the current String into lower case and returns.

To find whether a String contains a particular sub string irrespective of case −

  • Get the String.

  • Get the Sub String.

  • Convert the string value into lower case letters using the toLowerCase() method, store it as fileContents.

  • Convert the string value into lower case letters using the toLowerCase() method, store it as subString.

  • Invoke the contains() method on the fileContents by passing subString as a parameter to it.

Example

Assume we have a file named sample.txt in the D directory with the following content −

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.

Following Java example reads a sub string from the user an verifies whether the file contains the given sub string irrespective of case.

 Live Demo

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.");
      }
   }
}

Output

Enter the sub string to be verified:
comforts of their drawing rooms.
File contains the given sub string.
raja
Published on 11-Oct-2019 10:55:42
Advertisements