
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.
– Screenshot1.
– Screenshot2.
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.
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.
yes, ofcourse! there are 3 ways to solve this problem, I am sharing the simplest solution. You can also use a stack.
Thank you so much Shreya. I’ll take a look at all details and will update post with your recommendation tomorrow.
How to do without inbuilt function
Hi Sharan – we already have it in above example.
Just use method which says: // Implement your own Contains Method with Recursion
thank you very usefull
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++) "
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().
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
What is the time complexity of this algorithm?
what is the theme used here?
Hi Jack. I’m using Genesis Framework on crunchify.com
Curious why not use the already created ‘contains’ method? Is there a benefit to using your own?
Hi Dave,
Above example shows implementation of “contains” method only. Just incase in an interview, somebody ask us to implement the same..