Friday, August 20, 2021

How to check if String contains another SubString in Java? contains() and indexOf() example

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1. For example "fastfood".indexOf("food") will return 4 but "fastfood".indexOf("Pizza") will return -1. This is the easiest way to test if one String contains another substring or not.

The second method is lastIndexOf() which is similar to indexOf() but starts the search from the tail, but it will also return -1 if the substring is not found in the String or the last position of the substring, which could be anything between 0 and length -1.

The third method you can use to check if one String contains another in Java is contains() method of String. This method returns true if a substring is present in String, or false otherwise. The only difference between contains() and indexOf() is that the former returns a boolean value while later returns an int value.

Let's see some examples of contains() and indexOf() to demonstrate how you can use this method to search for a substring in a string in java.

And, If you are new to the Java world then I also recommend you go through The Complete Java MasterClass online course to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.





Searching Using indexOf

I have used indexOf() quite often to check if String contains a particular character or not, but it can obviously be used to check if a string contains another substring or not. Given this method expect a String, you can pass a single character string e.g. "a" or a substring e.g. "abc", technically speaking both are substring. What is more important is that the indexOf() method return -1 when the string on which indexOf() has been called doesn't contain the string passed as argument i.e. "abcd".indexOf("e") will return -1

here is how you can use indexOf() to test if String contains a character or substring in Java:

String input = "Android gave new life to Java";
boolean isFound = input.indexOf("Android") !=-1? true: false; //true

Similarly, you can check if String contains a particular character or not e.g.



boolean isExists = "iPhone".indexOf("i");

This will return 0, which is not -1 which means "iPhone" contains "i".

One important thing to note about the indexOf() and lastIndexOf() method is that both of them perform a case-sensitive search, which means if you search "iPhone".indexOf("I") it will return false. 

If you want to perform a case-insensitive search then you must convert both inputs and search String into the same case e.g. upper or lower case and then call the indexOf() method, as shown in our sample program. Please see Java: A Beginner's Guide by Herbert Schildt to learn more about String related methods in Java.

How to check if String contains another SubString in Java? contains() and indexOf() example




Searching using contains()

The contains() method provides the best way to check if String contains another substring or not. It reads well and returns boolean, which means you can directly use it inside if statements. The contains method returns true if and only if this string contains the specified sequence of char values. 

It also throws NullPointerException if the substring passed to it is null. The only issue with the contains() method is that it was added to Java 1.5, which means you cannot use it on the earlier version. On the other hand indexOf() method exists from JDK 1.0 so you can it everywhere.

here is an example of how to use the contains() method to check if one string contains another String in Java:

String test = "Java8 makes Java more powerful";
boolean isFound = text.contains("Java8"); // true

Similar to indexOf() this method also performs a case-sensitive search so if your input is in a different case then this will return false. If you want to do a case-insensitive search then use the same technique, convert both input and search string in the same case and then call the contains() method. 

If you are concerned about the performance of contains(), indexOf(), and lastIndexOf() method then please see these Java performance turning online courses and Java Performance The Definitive Guide book by Scott Oaks to learn more about performance testing and analysis.

How to check if String contains another SubString in Java?




Java Program to check if one String contains another

Here is our sample Java program to demonstrate how to use the indexOf() and contains() method to check if one String contains another substring in Java or not.

package hello;

public class SubStringProblem {

  public static void main(String[] args) {

    // 1st example - You can use the indexOf() method to check if
    // a String contains another substring in Java
    // if it does then indexOf() will return the starting index of
    // that substring, otherwise it will return -1

    System.out
        .println("Checking if one String contains another S
                      tring using indexOf() in Java");
    String input = "Java is the best programming language";
    boolean isPresent = input.indexOf("Java") != -1 ? true : false;

    if (isPresent) {
      System.out.println("input string: " + input);
      System.out.println("search string: " + "Java");
      System.out.println("does String contains substring? " + "YES");
    }

    // indexOf is case-sensitive so if you pass wrong case, you will get wrong
    // result
    System.out.println("Doing search with different case");
    isPresent = input.indexOf("java") != -1 ? true : false;
    System.out.println("isPresent: " + isPresent); // false because indeOf() is
                                                   // case-sensitive

    // 2nd example - You can also use the contains() method to check if
    // a String contains another String in Java or not. This method
    // returns a boolean, true if substring is found on String, or false
    // otherwise.
    // if you need boolean use this method rather than indexOf()
    System.out
        .println("Checking if one String contains another String 
                                  using contains() in Java");
    input = "C++ is predecessor of Java";
    boolean isFound = input.contains("Java");
    if (isFound) {
      System.out.println("input string: " + input);
      System.out.println("search string: " + "Java");
      System.out.println("does substring is found inside String? " + "YES");
    }

    // contains is also case-sensitive
    System.out.println("Searching with different case");
    isFound = input.contains("java");
    System.out.println("isFound: " + isFound); // false because indeOf() is
                                               // case-sensitive

  }
}

Output
Checking if one String contains another String using indexOf() in Java
input string: Java is the best programming language
search string: Java
does String contain substring? YES
Doing search with different case
isPresent: false
Checking if one String contains another String using contains() in Java
input string: C++ is the predecessor of Java
search string: Java
does substring is found inside String? YES
Searching for different case
isFound: false


Here is also a nice diagram to explain how indexOf works with positions of characters inside the String:

Java String  contains() and indexOf() example



That's all about how to check if one String contains another substring in Java. You can use any of the three methods, indexOf(), lastIndexOf(), or contains() to verify that. The general guideline is that to use indexOf() if you need the position of substring otherwise contains() is more readable and returns a boolean value which can be used in if conditions directly.

Other Java String tutorials you may like to explore
  • How to format a String in Java? (tutorial)
  • How to check if the given String is Numeric in Java? (solution)
  • How to parse String to float in Java? (tutorial)
  • Top 10 Java String Interview Questions with Answers (list)
  • How to split String by delimiter in Java? (tutorial)
  • How to replace String in Java? (example)
  • How to split a string by whitespace or tabs in Java? (tutorial)
  • How to add leading zeros to an Integer in Java? (tutorial)
  • How to join String by a delimiter in Java 8? (tutorial)
  • How to convert char to String in Java? (tutorial)
  • How to compare two String in Java? (tutorial)
  • When should you use the intern() method of String? (article)
  • How to concatenate String in Java? (example)
  • How to convert String to Date in Java? (tutorial)
  • The right way to check if String is empty in Java? (tutorial)
P. S. - Let me know if you come across any other way to check if a string contains a substring or not. Also, if you are learning Java from scratch then I suggest sticking with a good book like Java: How to Program by Dietel to learn fundamentals before jumping around.

5 comments :

Unknown said...

Thank you :)

Obaid said...

boolean isFound = input.indexOf("Android") !=-1? true: false; //true

// for the line above the below statement is enough

isFound = ( input.indexOf("Android") != -1 ); //parenthesis are additional,
// != will always evaluate to a boolean.

Anonymous said...

In my case .contains(),isExist are not working and also no error showing to me after using it.
I have set of url and I have substring to search from that URL and print wheater it is exist or not

Unknown said...

You made a mistake in article

Searching using contains section :

String test = "Java8 makes Java more powerful";

boolean isFound = test.contains("Java8"); #text

javin paul said...

Ah, text vs test :-) spell checker magic

Post a Comment