This post will discuss how to check if a String is a substring of another String in Java.

1. Using String#contains() method

The standard solution to check if a string is a substring of another string is using the String#contains() method. It returns true if the string contains the specified string, false otherwise.

Download  Run Code

2. Using String#indexOf() method

The indexOf() method returns the index of the first appearance of the specified substring in the string, and returns -1 if the substring is not found. You can use it as follows:

Download  Run Code

3. Using StringUtils class

If you prefer Apache Common StringUtils class for operations on a String, you can use its contains() method to determine if a string contains another string or not. If case doesn’t matter, use StringUtils.containsIgnoreCase() for comparison. Note, both these methods are null-safe.

Download Code

4. Using Regex

You can even use a regular expression to find a substring within a string. The idea is to create a matcher to match a string for the specified substring. This is demonstrated below:

Download  Run Code

 
You can make the search case-insensitive by compiling the regular expression into a pattern with the CASE_INSENSITIVE flag, as shown below:

Download  Run Code

That’s all about checking if a String is a substring of another String in Java.