Search code examples
javacharat

Find how many times the text in one line repeats in another


A task is given: Find how many times the text in the PATTERN is repeated in the TEXT. Repetitions may overlap with each other. We propose to cycle through all possible positions in TEXT in which the PATTERN can begin. When iterating, check each position in a loop, iterating over the characters in the PATTERN and the characters that go from the position being iterated. If at least one of the characters does not match during the check, the position does not fit and we move on to the next one. Otherwise, you need to increase the repetition count.

I understand that in order to find out which character is at the i-th position in the string, use the charAt(i) method, which each object of the String type has.

But what exactly, categorically does not come to mind.

public class Main {
    public static final String TEXT = "aaababaabaaaabaabaabaabaaababaabaaababaabaaaabaabaabaabbabaabaaababaababaabaabaabaaabbaab";
    public static final String PATTERN = "aab";

    public static void main(String[] args) {
        int count = 0;

        for (int i = 0; i < TEXT.length(); i++) {
          int count = 1;
           
        }

        System.out.println("String " + PATTERN + " met in the text " + count + " times");
    }
}

Solution

  • For every i position of TEXT, you need to look the n (pattern length) chars if they match the pattern chars, using iteration on them

    int count = 0;
    boolean positionOk;
    for (int i = 0; i < TEXT.length(); i++) {
        positionOk = true;
        for (int j = 0; j < PATTERN.length(); j++) {
            if (TEXT.charAt(i + j) != PATTERN.charAt(j)) {
                positionOk = false;
                break;
            }
        }
    
        if (positionOk) {
            count += 1;
        }
    }
    

    If you didn't need to it with iterating, you could just use String.startsWith(word, position)

    for (int i = 0; i < TEXT.length(); i++) {
        if (TEXT.startsWith(PATTERN, i)) {
            count += 1;
        }
    }