Pick a
string searching algorithm[
^]
Pick an
online tutorial[
^]
You should now have enough info to solve your problem
[Edit] Your attempted solution is not quite right - the issues are
1. You are using hard coded lengths, use the
string.length()
method instead
2. You seem to have the
smallString
&
bigString
the wrong way round in the inner comparison loop. I assume that you are searching for smallString inside bigString
3. You are not incrementing the index for the big string in the inner loop - the index should be
start + j
4. The matching part of the algorithm is fatally flawed. If the first character in the small string matches then you set
flag
to
true
. If the second character doesn't match then
flag
will still be
true
. Instead set
flag
to
true
before the inner loop and if there is a character mismatch, then set
flag
to
false
and break from the inner loop (once one character fails, there is no need to continue)
5. The output is displaying both strings, I think you probably want to display where the substring starts at as well , i.e.
start
6. If the string is not found then you will get an array indexing error, the upper bound of the outer loop should be
bigString.length() - smallString.length() + 1
Updated version:
public class subString
{
static public void checkSubString(String smallString, String bigString)
{
int start;
boolean flag;
for (int i = 0; i < bigString.length() - smallString.length() + 1; i++)
{
start=i;
flag=true;
for (int j= 0; j < smallString.length(); j++)
{
if(bigString.charAt(start + j) != smallString.charAt(j))
{
flag=false;
break;
}
}
if(flag)
{
System.out.println("( "+smallString+" is subString of " + bigString + " from position " + start + ")");
break;
}
}
}
}