I am trying to implement a substring method using only charAt method of the String class
The problem occurs when I include the last character in the search term 'hat.' otherwise everything works perfectly.
Also when searching for example for 'hat' I see the charAt(j) trace prints all 'h' with index 0 for all characters and true occurrence.
Here is the complete code:
public class SubString {
public static void main(String[] args) {
String line = "The cat in the hat.";
String item = "hat.";
System.out.println("'" + item + "' is substring of '" + line + "' : " + isSubString(item, line));
}
private static boolean isSubString(String item, String line) {
int i = 0;
int j = 0;
int count = 0;
for (i = 0; i < line.length() - item.length(); i++) {
for (j = 0; j < item.length(); j++) {
if (item.charAt(j) != line.charAt(i + j)) {
break;
}
if (item.charAt(j) == line.charAt(i + j)) {
System.out.println(item.charAt(j) + ":" + j + " - " + line.charAt(i + j) + ":" + (i + j));
count++;
}
if (count == item.length())
return true;
}
}
return false;
}
}
Again the problem occurs when searching for 'hat.' < == the last word with dot.
and the 'hat' which although return true but trace shows wrong characters ( only h's compared) and indexes are always 0.