Since you are working on an exercise, I wouldn't fix your code, but help you fix it yourself.
First, some basics: in Java you use charAt(i)
to access an individual character. For example,
char ch = Text1.charAt(3);
gets you the forth character from the beginning of the string (indexes are zero-based).
Now for the algorithm: you want to iterate through all positions of the second string with enough characters after it to make a match with the first string possible. This means that the index goes from zero, inclusive, to the position Text2.length()-Text1.length()
, exclusive. This is the starting position of the potential match - let's call it p
.
Given a position p
, you want to iterate through all characters of Text1
starting at zero, and compare them to Text2
characters starting with the character at position p
. Let's say the index in Text1
is called i
, and it goes from zero, inclusive, to Text1.length()
, exclusive. Then you want to compare Text1.getChar(i)
for equality with Text1.charAt(i+p)
.
You need to finish the comparison with all characters of Text1
before you declare a match. You need to know the result in the outer loop, so you want to use a bool
flag. Set the flag to true
before the inner loop. If you see a mismatch, set the flag to false
, and break out of the loop.
If the flag is true
after the inner loop, increment the counter.