Consider you have been told to implement a kind of the java String.substring method.
The signature of the method is as follows:
public static boolean isSubstring(String i_StringForSearch, String i_SubStringToFind)
Here is my solution, but I feel it's still not the best elegant solution I could have.(Many canonical if else's)
What do you think? Would you do it in another way?
public static boolean isSubstring(String i_StringForSearch, String i_SubStringToFind)
{
int strForSearchIndex = 0;
int subStrToFindIndex = 0;
boolean endOfStringToSearch = false;
boolean foundSubString = false;
boolean isThereASequenceOfMatching = false;
while(!endOfStringToSearch && !foundSubString)
{
if(strForSearchIndex == i_StringForSearch.length())
{
endOfStringToSearch = true;
}
else if(i_StringForSearch.charAt(strForSearchIndex) == i_SubStringToFind.charAt(subStrToFindIndex))
{
isThereASequenceOfMatching = true;
if(subStrToFindIndex == i_SubStringToFind.length() -1 )
{
foundSubString = true;
}
subStrToFindIndex++;
strForSearchIndex++;
}
else if(i_StringForSearch.charAt(strForSearchIndex) != i_SubStringToFind.charAt(subStrToFindIndex))
{
if(isThereASequenceOfMatching)
{
subStrToFindIndex = 0;
isThereASequenceOfMatching = false;
}
strForSearchIndex++;
}
}
return foundSubString;
}
containsthansubstringto me.substringhas a very clearly understood purpose, which is very different from what's here.