Grails Cookbook - A collection of tutorials and examples

Check If String Contains Substringin Java

In Java, we can confirm if one String holds a specific substring. For example, we would like to check if the substring "rhapsody" is in the String "Bohemian rhapsody movie". Check out the examples on how to use Java String's contains method.


This syntax will show you how the method contains() works. Understand that this method will check if a specified character sequence is in a String. Kindly check out the syntax shown below:

public boolean contains(CharSequence s);
What you just observed is the method that confirms the given parameter on the String instance is a substring, and returns a boolean value. When that specific character sequence is spotted, you will get a true value, otherwise the returned value is false.

Implementation Of The Method

Checking the source code (Java 1.5 at the time of writing) is shown below:
    public boolean contains(CharSequence s) {
        return indexOf(s.toString()) > -1;
    }
The CharSequence is converted to a String, afterwards, it calls the attention of indexOf method. This type of method will get you a 0 or higher number if it locates the String you're looking for, or else, the returned value is -1.

Let's Analyze A Simple Program

Check out and observe below the written simple example. We will learn how to utilize the contains method of Java String class:
/**
 * This is a simple example that will show you if one String contains another substring.
 */
public class Test {
    public static void main(String[] args) {
        String phrase = "Bohemian rhapsody movie";
        String frstWord = "rhapsody";
        String secndWord = "queen";
        System.out.println("The phrase is: " + phrase);
        System.out.println("Is there a rhapsody in the phrase? " + phrase.contains(frstWord));
        System.out.println("Is there a queen in the phrase? " + phrase.contains(secndWord));
    }
}
Let's run this program and see what's the result:
The phrase is: Bohemian rhapsody movie
Is there a rhapsody in the phrase? true
Is there a queen in the phrase?  false
As seen in the output, the returned value is true, this is because the String "rhapsody" is found in the phrase. And since the word "queen" is not indicated within the phrase, we got a false value.

Warning: Case Sensitivity

There is a danger zone in every programming process, we should be aware that contains method is case sensitive. With that being said, we should carefully check if the String we'd like to find is equivalent in each letter including the case. Observe below the writen simple example that shows the case sensitivity:

public class Test { public static void main(String[] args) { String phrase = "Bohemian rhapsody movie"; System.out.println("First test: Is there a Rhapsody in the phrase? " + phrase.contains("Rhapsody")); System.out.println("Second test:Is there a rhapsody in the phrase? " + phrase.contains("rhapsody")); } }

This is the result of the test we've tried:
First test: Is there a Rhapsody in the phrase? false
Second test: Is there a rhapsody in the phrase? true

Although we're looking for the specific rhapsody word, the returned value was false because we have typed it with a capital letter. And since that is not exactly alike with each letter, it's expected expression will be untrue. This is not the case for the second test. We encoded the rhapsody string as equivalent to the rhapsody word written in the String phrase, thus, making the value true.

Case Insensitive

There is a way to verify if a String contains a character sequence through case insentive procedure. When we want to look for that character, one solution is that we can adjust our code by converting both Strings to uppercase or to lowercase prior to the test. Observe the written example below:
/**
 * This is a simple example that shows case insensitive matching using contains.
 */
public class Test {
    public static void main(String[] args) {
        String phrase = "Bohemian rhapsody movie";
        String word = "rhApsody";
        System.out.println("First test: " + phrase.contains(word));
        System.out.println("Second test: " + phrase.toLowerCase().contains(word.toLowerCase()));
    }
}
The expected result will be:
First test: false
Second test: true
Notice that the word we searched is in mixed case. What we need to do is to convert the string word to lower case thereby making it case insensitive. You will get the same result when you try this with the upper case.

public class Test { public static void main(String[] args) { String phrase = "Bohemian rhapsody movie"; String word = "rhApsody"; System.out.println("First test: " + phrase.contains(word)); System.out.println("Second test: " + phrase.toUpperCase().contains(word.toUpperCase())); } }

Check the same result as we've seen above:

First test: false
Second test: true

What is CharSequence

There are different implementation of CharSequence that contains can accept. And by this, we are not limited on passing only String parameter. Check out below the written examples on how the implementation works.

This is a simple example of using Java String's contain method against a CharBuffer parameter:

import java.nio.CharBuffer;
/**
 * This is a simple example that demonstrates the process of using contains with CharBuffer.
 */
public class Test {
    public static void main(String[] args) {
        String phrase = "Bohemian rhapsody movie";
        CharBuffer cb = CharBuffer.allocate(8);
        cb.append('r');
        cb.append('h');
        cb.append('a');
        cb.append('p');
        cb.append('s');
	cb.append('o');
	cb.append('d');
	cb.append('y');
        cb.clear();
        System.out.println("This is what Char Buffer holds: " + cb.toString());
        System.out.println("Contains result: " + phrase.contains(cb));
    }
}

The expected result will be:
This is what Char Buffer holds: rhapsody
Contains result: true
And now observe this example of utilizing Java String's contain method against a StringBuilder paramenter:
public class Test {
    public static void main(String[] args) {
        String phrase = "Bohemian rhapsody movie";
        StringBuilder sb = new StringBuilder();
	sb.append('r');
        sb.append('h');
        sb.append('a');
        sb.append('p');
        sb.append('s');
	sb.append('o');
	sb.append('d');
	sb.append('y');
        System.out.println("This is what StringBuilder holds: " + sb.toString());
        System.out.println("Contains result: " + phrase.contains(sb));
    }
}
The output of the code will show you this:
This is what StringBuilder holds: rhapsody
Contains result: true
Now we've covered the parameters CharBuffer and StringBuilder, another parameter is StringBuffer. Below is an example of implementing Java String's contain method against a StringBuffer parameter:
/**
 * This is a simple example that demonstrates the process of using contains with StringBuffer.
 */
public class Test {
    public static void main(String[] args) {
        String phrase = "Bohemian rhapsody movie";
        StringBuffer sb = new StringBuffer();
	sb.append('r');
        sb.append('h');
        sb.append('a');
        sb.append('p');
        sb.append('s');
	sb.append('o');
	sb.append('d');
	sb.append('y');
        System.out.println("This is what StringBuffer holds: " + sb.toString());
        System.out.println("Contains result: " + phrase.contains(sb));
    }
}
This is what StringBuffer holds: rhapsody
Contains result: true