How to Check If a String Contains a Specific Substring in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a string contains a specific substring in Java. We will explore different methods for this common task, starting with the straightforward contains() method. You will learn how to use contains() to determine if a string includes a given sequence of characters and practice implementing this in a simple Java program.

Following the introduction to contains(), the lab will guide you through using the indexOf() method to not only check for the presence of a substring but also to find its position within the string. Finally, you will learn techniques to perform case-insensitive substring checks, ensuring your code can handle variations in capitalization. By the end of this lab, you will have a solid understanding of various approaches to substring checking in Java.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/StringManipulationGroup(["String Manipulation"]) java(("Java")) -.-> java/SystemandDataProcessingGroup(["System and Data Processing"]) java/StringManipulationGroup -.-> java/strings("Strings") java/SystemandDataProcessingGroup -.-> java/string_methods("String Methods") subgraph Lab Skills java/strings -.-> lab-559979{{"How to Check If a String Contains a Specific Substring in Java"}} java/string_methods -.-> lab-559979{{"How to Check If a String Contains a Specific Substring in Java"}} end

In this step, we will learn how to check if a string contains a specific substring in Java using the contains() method. This is a common task in programming, for example, when searching for a keyword in a sentence or checking if a file name contains a certain extension.

The contains() method is part of the String class in Java. It returns true if the string contains the specified sequence of characters, and false otherwise.

Let's create a new Java file to practice using contains().

  1. Open the File Explorer on the left side of the WebIDE.

  2. Make sure you are in the ~/project directory.

  3. Right-click in the empty space and select "New File".

  4. Name the new file StringContains.java.

  5. Open the StringContains.java file in the editor.

  6. Copy and paste the following code into the editor:

    public class StringContains {
        public static void main(String[] args) {
            String sentence = "Java programming is fun and powerful.";
            String keyword = "programming";
    
            // Check if the sentence contains the keyword
            boolean containsKeyword = sentence.contains(keyword);
    
            System.out.println("Sentence: \"" + sentence + "\"");
            System.out.println("Keyword: \"" + keyword + "\"");
            System.out.println("Does the sentence contain the keyword? " + containsKeyword);
    
            String anotherKeyword = "Python";
            boolean containsAnotherKeyword = sentence.contains(anotherKeyword);
    
            System.out.println("\nAnother keyword: \"" + anotherKeyword + "\"");
            System.out.println("Does the sentence contain the another keyword? " + containsAnotherKeyword);
        }
    }

    In this code:

    • We declare a String variable sentence and a String variable keyword.
    • We use sentence.contains(keyword) to check if sentence contains the sequence of characters in keyword. The result is stored in a boolean variable containsKeyword.
    • We print the original sentence, the keyword, and the result of the contains() check.
    • We repeat the process with a different keyword, "Python", to see the result when the substring is not found.
  7. Save the file (Ctrl+S or Cmd+S).

  8. Open the Terminal at the bottom of the WebIDE.

  9. Make sure you are in the ~/project directory using the command:

    cd ~/project
  10. Compile the Java program using the javac command:

    javac StringContains.java

    If there are no errors, you will not see any output. A StringContains.class file will be created in the ~/project directory.

  11. Run the compiled Java program using the java command:

    java StringContains

    You should see output similar to this:

    Sentence: "Java programming is fun and powerful."
    Keyword: "programming"
    Does the sentence contain the keyword? true
    
    Another keyword: "Python"
    Does the sentence contain the another keyword? false

This output shows that the contains() method correctly identified that the sentence contains "programming" but not "Python".

Explore indexOf() for Substring Position

In the previous step, we learned how to check if a string contains a substring using contains(). Now, let's explore another useful method, indexOf(), which not only tells us if a substring exists but also gives us its starting position within the string.

The indexOf() method in Java's String class returns the index within the string of the first occurrence of the specified substring. The index is the position of the first character of the substring. Remember that in programming, indexing usually starts from 0. If the substring is not found, indexOf() returns -1.

Let's modify our previous Java file, StringContains.java, to use the indexOf() method.

  1. Open the StringContains.java file in the WebIDE editor.

  2. Replace the entire contents of the file with the following code:

    public class StringContains {
        public static void main(String[] args) {
            String sentence = "Java programming is fun and powerful.";
            String keyword = "programming";
    
            // Find the index of the keyword
            int index = sentence.indexOf(keyword);
    
            System.out.println("Sentence: \"" + sentence + "\"");
            System.out.println("Keyword: \"" + keyword + "\"");
    
            if (index != -1) {
                System.out.println("The keyword \"" + keyword + "\" was found at index: " + index);
            } else {
                System.out.println("The keyword \"" + keyword + "\" was not found.");
            }
    
            String anotherKeyword = "Python";
            int anotherIndex = sentence.indexOf(anotherKeyword);
    
            System.out.println("\nAnother keyword: \"" + anotherKeyword + "\"");
    
            if (anotherIndex != -1) {
                System.out.println("The keyword \"" + anotherKeyword + "\" was found at index: " + anotherIndex);
            } else {
                System.out.println("The keyword \"" + anotherKeyword + "\" was not found.");
            }
        }
    }

    In this updated code:

    • We use sentence.indexOf(keyword) to find the starting index of the keyword within the sentence. The result is stored in an int variable index.
    • We use an if statement to check if the returned index is -1. If it's not -1, it means the keyword was found, and we print its index. Otherwise, we print a message indicating that the keyword was not found.
    • We repeat the process for "Python" to demonstrate the case where the substring is not present.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Open the Terminal at the bottom of the WebIDE.

  5. Make sure you are in the ~/project directory.

  6. Compile the modified Java program:

    javac StringContains.java
  7. Run the compiled Java program:

    java StringContains

    You should see output similar to this:

    Sentence: "Java programming is fun and powerful."
    Keyword: "programming"
    The keyword "programming" was found at index: 5
    
    Another keyword: "Python"
    The keyword "Python" was not found.

The output shows that "programming" starts at index 5 in the sentence (remembering that 'J' is at index 0, 'a' is at index 1, and so on, including the space). It also correctly indicates that "Python" was not found.

Using indexOf() is a powerful way to not only check for the presence of a substring but also to determine its exact location, which can be useful for various string manipulation tasks.

Make Substring Check Case-Insensitive

In the previous steps, we used contains() and indexOf() to search for substrings. However, these methods are case-sensitive. This means that "Java" is considered different from "java" or "JAVA". In many situations, you might want to perform a case-insensitive search.

Java's String class doesn't have a built-in method like containsIgnoreCase() or indexOfIgnoreCase(). However, we can achieve case-insensitivity by converting both the original string and the substring to the same case (either lowercase or uppercase) before performing the search. The most common approach is to convert both to lowercase using the toLowerCase() method.

Let's modify our StringContains.java file again to perform a case-insensitive search.

  1. Open the StringContains.java file in the WebIDE editor.

  2. Replace the entire contents of the file with the following code:

    public class StringContains {
        public static void main(String[] args) {
            String sentence = "Java programming is fun and powerful.";
            String keyword = "JAVA"; // Using uppercase for demonstration
    
            // Convert both strings to lowercase for case-insensitive comparison
            String lowerSentence = sentence.toLowerCase();
            String lowerKeyword = keyword.toLowerCase();
    
            // Use contains() on the lowercase strings
            boolean containsKeyword = lowerSentence.contains(lowerKeyword);
    
            System.out.println("Original Sentence: \"" + sentence + "\"");
            System.out.println("Original Keyword: \"" + keyword + "\"");
            System.out.println("Does the sentence contain the keyword (case-insensitive)? " + containsKeyword);
    
            // You can also use indexOf() in a case-insensitive way
            int index = lowerSentence.indexOf(lowerKeyword);
    
            if (index != -1) {
                System.out.println("The keyword \"" + keyword + "\" was found at index (case-insensitive): " + index);
            } else {
                System.out.println("The keyword \"" + keyword + "\" was not found (case-insensitive).");
            }
        }
    }

    In this code:

    • We define the keyword as "JAVA" (uppercase).
    • We create new strings lowerSentence and lowerKeyword by converting the original strings to lowercase using toLowerCase().
    • We then use the contains() method on the lowercase strings to perform a case-insensitive check.
    • We also demonstrate how to use indexOf() in a case-insensitive manner by applying it to the lowercase strings.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Open the Terminal at the bottom of the WebIDE.

  5. Make sure you are in the ~/project directory.

  6. Compile the modified Java program:

    javac StringContains.java
  7. Run the compiled Java program:

    java StringContains

    You should see output similar to this:

    Original Sentence: "Java programming is fun and powerful."
    Original Keyword: "JAVA"
    Does the sentence contain the keyword (case-insensitive)? true
    The keyword "JAVA" was found at index (case-insensitive): 0

This output shows that even though the original keyword was "JAVA" (uppercase), the case-insensitive search correctly found it in the sentence and reported its index (which is 0 for "Java" in lowercase).

By converting strings to a consistent case before searching, you can easily perform case-insensitive substring checks in Java.

Summary

In this lab, we learned how to check if a string contains a specific substring in Java. We started by using the contains() method, which provides a simple boolean check for the presence of a substring. This method is straightforward and useful for basic substring existence checks.

We then explored the indexOf() method, which not only checks for the presence of a substring but also returns the starting index of the first occurrence. This allows for more detailed analysis of the substring's position within the string. Finally, we addressed the common requirement of performing case-insensitive substring checks, demonstrating techniques to achieve this regardless of the original string's casing.