1

This program is intended to match a string to another string and calculate the number common substrings they share. For some reason, it always prints the same incorrect values. Using the same methods, how can I make this code work as I intended it to?

public static void main(String[] args) {
        String secret = "word";
        String guess = "gzek";
        int count = 0;
        int length = secret.length();
        int guess_length = guess.length();
        for(int i=0;i<length-1;i++){
            if(secret.substring(i, i).equals(guess.substring(i, i))){
                count ++;
            }
        }
        System.out.println(count);
    }
  • 3
    What do you think `secret.substring(i, i)` is? – khelwood Apr 26 '22 at 19:14
  • See [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173) – Bohemian Apr 26 '22 at 19:17
  • What do you mean by common sub-strings? Do you by any chance mean the number of common characters? To get the i-th character from a string, you can use string.charAt(i). – Michel K Apr 26 '22 at 19:48
  • *the number common substrings* - Only by looking at your code (*which doesn't seem to be meant to count common substring*) and this problem statement, it is not clear what you're trying to achieve. You should [edit your question](https://stackoverflow.com/posts/72019277/edit) by providing it with an example. I.e. post two words that are long enough to illustrate the principle and list all substring that need to be counted in these words. – Alexander Ivanchenko Apr 26 '22 at 20:14

1 Answers1

0

According to its JavaDoc, the end index parameter of the substring() method is exclusive:

@param      beginIndex   the beginning index, inclusive.
@param      endIndex     the ending index, exclusive.

This means that secret.substring(i, i) returns the sub-string from i to i-1, which is always the empty string "". Therefore, secret.substring(i, i).equals(guess.substring(i, i)) always compares "" with "" and is always true. Your code effectively counts the number of characters in guess.

If you want to compute all sub-strings of a string s, you need two loops, one for the start index and one for the end index:

for (int i = 0; i < s.length(); i++) {
    for (int j = i; j < s.length(); j++) {
        String substring = s.substring(i, j + 1); 
        // further code ...
    }
}

Note that this only computes the sub-strings of one string. If I understood your question correctly, you want to compute all common sub-strings of two strings. To do this, you will need a total of four nested loops. This is going to be very slow even for small strings. There are of course much faster approaches, but they are also more complex.

Michel K
  • 411
  • 1
  • 7