How to Check if a String Contains a Substring? indexOf(), contains() and custom implementation

Last updated
App Shah

Crunchify » Java and J2EE Tutorials » How to Check if a String Contains a Substring? indexOf(), contains() and custom implementation

How to Check if a String Contains a Substring

I have two Strings: str1 and str2. How to check if str2 is contained within str1? You can definitely use Java’s own .contains()  method.

In Java, there are several ways to check if a string contains a substring. The most common approach is to use the indexOf method of the String class:

public static boolean containsSubstring(String str, String subStr) {
    return str.indexOf(subStr) != -1;
}

This method returns true if the subStr is found within the str and false otherwise. The indexOf method returns the index of the first occurrence of the substring within the string. If the substring is not found, it returns -1.

Another common approach is to use the contains method of the String class, which was added in Java 1.5:

public static boolean containsSubstring(String str, String subStr) {
    return str.contains(subStr);
}

This method is more concise and returns true if the subStr is found within the str and false otherwise.

Implement your own findMe method.

Here by this program we will implement contains() method. Let’s call it as findMe(String subString, String mainString). Find below implementation.

package com.crunchify.tutorials;

/**
 * @author crunchify.com
 */

public class CrunchifyFindString {

    public static void main(String[] args) {
        System.out.println("\nResult = "
                + findMe(" findMe", "Can you findMe from this String?"));
    }

    public static boolean findMe(String subString, String mainString) {
        boolean foundme = false;
        int max = mainString.length() - subString.length();

        // Java's Default "contains()" Method
        System.out.println(mainString.contains(subString) ? "mainString.contains(subString) Check Passed.."
                : "mainString.contains(subString) Check Failed..");

        // Implement your own Contains Method with Recursion
        checkrecusion: for (int i = 0; i <= max; i++) {
            int n = subString.length();

            int j = i;
            int k = 0;

            while (n-- != 0) {
                if (mainString.charAt(j++) != subString.charAt(k++)) {
                    continue checkrecusion;
                }
            }
            foundme = true;
            break checkrecusion;
        }
        System.out
        .println(foundme ? "\nImplement your own Contains() Method - Result: Yes, Match Found.."
                : "\nImplement your own Contains() Method - Result:  Nope - No Match Found..");
        return foundme;
    }
}

Eclipse Console result

Result-1:

mainString.contains(subString) Check Passed..

Implement your own Contains() method - Result: Yes, Match Found..

Result = true

Result-2: (notice blank space between find and Me)

mainString.contains(subString) Check Failed..

Implement your own Contains() Method - Result:  Nope - No Match Found..

Result = false

Let me know if you know any better way to implement this.

18 thoughts on “How to Check if a String Contains a Substring? indexOf(), contains() and custom implementation”

  1. package com.maven.practice;
    
    import java.util.Scanner;
    public class Test {
    
    	public static void main(String[] args) {
    		
    		try{
    			 Scanner scanner=new Scanner(System.in);
    		 	 String mainString=scanner.next();
    		 	 String subString=scanner.next();
    		 	 scanner.close();
    		 	 System.out.println("substring present in main string? : " +containSubString(mainString,subString));
    		 }
    		 catch(Exception e)
    		 {
    			 System.out.println("enter valid input");
    		 }
    		 
    	}
    	
    	public static boolean containSubString(String mainString, String subString)
    	{
    		int lengthMain=mainString.length();     //length of main string
    		int lengthSub=subString.length();        //length of sub string
    		char main[]=mainString.toCharArray();     //convert string to char array
    		char sub[]=subString.toCharArray();
    		int k=0, j=0;
    		while(k<lengthMain)         //loop to traverse the main string
    		{
    			int i=k;
    			while(j<lengthSub)       //loop for substring
    			{
    				if(main[i]!=sub[j])
    				{
    					
    					j=0;
    					break;
    				}
    				else
    				{
    					i++;  j++;
    				}
    				
    			}
    			k++;
    			if(j==lengthSub)
    			{
    				System.out.println("substring present at index" +(k-1)); //cuz starting index is zero
    				return true;
    			}
    		}
    		return false;
    	}
    }

    Screenshot1.
    Screenshot2.

    Reply
  2. if you watch the code carefully it does not work, you need to update your code for condition where you need to back track the matching process as in this case, consider “aabbc” as the substring and the main string is “aaabbcc”, the substring is present in this main string but your code will make it false as soon as it encountered with the third ‘a’ in the main string.

    Reply
    • Hi Shreya – thanks for your feedback. Nice corner case. Would you be so kind to provide a fix for this scenario? Looking forward for your update.

      Also, If you have nice idea about new tutorials then let us know as we are encouraging Guest post authors for Java language.

      Reply
      • yes, ofcourse! there are 3 ways to solve this problem, I am sharing the simplest solution. You can also use a stack.

        Reply
        • Thank you so much Shreya. I’ll take a look at all details and will update post with your recommendation tomorrow.

          Reply
      • package com.maven.practice;
        
        import java.util.Scanner;
        public class Test {
        
        	public static void main(String[] args) {
        		
        		try{
        			 Scanner scanner=new Scanner(System.in);
        		 	 String mainString=scanner.next();
        		 	 String subString=scanner.next();
        		 	 scanner.close();
        		 	 System.out.println("substring present in main string? : " +containSubString(mainString,subString));
        		 }
        		 catch(Exception e)
        		 {
        			 System.out.println("enter valid input");
        		 }
        		 
        	}
        	
        	public static boolean containSubString(String mainString, String subString)
        	{
        		int lengthMain=mainString.length();
        		int lengthSub=subString.length();
        		System.out.println(lengthSub);
        		char main[]=mainString.toCharArray();
        		char sub[]=subString.toCharArray();
        		
        		int k=0, j=0;
        		while(k<lengthMain)
        		{
        			int i=k;
        			while(j<lengthSub)
        			{
        				if(main[i]!=sub[j])
        				{
        					
        					j=0;
        					break;
        				}
        				else
        				{
        					i++;
        					j++;
        				}
        				
        			}
        			k++;
        			
        			if(j==lengthSub)
        			{
        				System.out.println("substring present at index" +(k-1)); //cuz starting index is zero
        				return true;
        			}
        			
        		}
        		return false;
        		
        	}
        	
        }
        Reply
      • package com.maven.practice;
        
        import java.util.Scanner;
        public class Test {
        
        	public static void main(String[] args) {
        		
        		try{
        			 Scanner scanner=new Scanner(System.in);
        		 	 String mainString=scanner.next();
        		 	 String subString=scanner.next();
        		 	 scanner.close();
        		 	 System.out.println("substring present in main string? : " +containSubString(mainString,subString));
        		 }
        		 catch(Exception e)
        		 {
        			 System.out.println("enter valid input");
        		 }
        	}
        	
        	public static boolean containSubString(String mainString, String subString)
        	{
        		int lengthMain=mainString.length();
        		int lengthSub=subString.length();
        		System.out.println(lengthSub);
        		char main[]=mainString.toCharArray();
        		char sub[]=subString.toCharArray();
        		
        		int k=0, j=0;
        		while(k<lengthMain)
        		{
        			int i=k;
        			while(j<lengthSub)
        			{
        				if(main[i]!=sub[j])
        				{
        					
        					j=0;
        					break;
        				}
        				else
        				{
        					i++;
        					j++;
        				}				
        			}
        			k++;			
        			if(j==lengthSub)
        			{
        				System.out.println("substring present at index" +(k-1)); //cuz starting index is zero
        				return true;
        			}			
        		}
        		return false;		
        	}	
        }
        Reply
    • Hi Sharan – we already have it in above example.

      Just use method which says: // Implement your own Contains Method with Recursion

      Reply
  3. Why did you use “max” instead of just using mainString.length() in the for loop. By using “max” we will be reducing the total number of characters to be checked, yes? What if the subString is present at the end of the mainString. I don’t get it. Explain? –
    ” checkrecusion: for (int i = 0; i <= max; i++) "

    Reply
    • Hi Aniruddha – here max is a difference between mainString and subString and that’s the max we need to iterate through loop. Here max value will be always less than mainString.lenght().

       max = mainString.length() - subString.length(); 
      Reply
  4. This is wrong. Your program doesn’t work for duplicates.. it does not work if a string contains duplicate characters. try it with substring = “aab” and main string = “aaab”

    it gives false while it should be true.

    The contains function should be implemented using suffix trees

    Reply
    • Hi Dave,
      Above example shows implementation of “contains” method only. Just incase in an interview, somebody ask us to implement the same..

      Reply

Leave a Comment