-2

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.

Abu Muhammad
  • 1,185
  • 5
  • 20
  • 29

2 Answers2

1

The first loop omits the last character of the string. i.e, line.length() - item.length()

Please replace it with below for loop condition.

for (i = 0; i < line.length() - item.length() + 1; i++) {            
Rolson Quadras
  • 446
  • 3
  • 8
-1

you should try

line.contains(item)
Serjik
  • 10,543
  • 8
  • 61
  • 70
V.ERNST
  • 79
  • 4