Others suggested using String.contains() - this is java.lang code, not a Java library. However, you obviously want to learn how you could do it yourself. One way to do this is to look at the source code of OpenJDK 7 on String.contains() , which uses String.indexOf() under covers. You can see the (fairly simple) algorithm that they use there.
Problem with your code
Interestingly, your code works for "rahul" and "rararahul" when I embed it in my dev environment. However, there is an infinite loop in the event of a mismatch. This will happen for any str2 containing any of the characters str1 . This is because as soon as you find a match for any character in str1 on the string str2, you reset your variables to start over. Actually, your output is enough to debug it if you look at the sequence that goes through each line.
Possible fix
If you want to continue your own approach and learn from it, then consider stopping and making a small paper design your own approach. You are looking for str1 to appear in str2 . Therefore, you probably want to swap your loops. Then you can be more effective. You can traverse the longer character String ( str2 ) by a character in the outer loop. Then you really need to go into the inner loop if the first character of the shorter line ( str1 ) matches the character you are working with in str2 .
eg. for a bit of your code loop
boolean retFound = false; for (int jj = 0; jj < len2; jj++) { if (arr1[0] == arr2[jj]) { boolean tempFound = true; int foundIndex = jj; for (int ii = 0; ii < len1; ii++) { if (arr1[ii] != arr2[jj+ii]) { tempFound = false; break; } } if (tempFound) { System.out.println("Found substring " + str1 + " in " + str2 + " at index " + foundIndex); System.out.println("Carrying on to look for further matches..."); tempFound = false; retFound = true; } } } return retFound;
Please note: this will not be fast, but it should work. I tested all the string patterns you provided. You also get a bonus - he will find several matches. If you do not want this (just want true false), break out when he says "Continuing to search ..."
As others have said, if you want to continue your source code, of course, do not try to change the loop variables (i.e. ii) in the inner loop. This is a bad practice, hard to read and prone to many mistakes.
source share