1

I want to write a program that figures out how many times a certain set of characters repeats itself in a longer set of characters (several times for several different set of characters)

I tried to achieve this by "importing" the long set of characters into a char array, and then make a 2D array for all the shorter sets of characters that I want to check the occurence of.

Then, I wanted my for loop to create an "interim" array of the same length as the short arrays have and compare it to each of them, however, the program keeps returning 0 occurences no matte what... And is also taking too long to compute when checking longer arrays with loads of character sets.

import java.util.*;
public class A {

public static void main (String [] args) {
    Scanner sc = new Scanner (System.in);

    //Preberi podatke
    int dolzinaDolgi = sc.nextInt(); //D
    int dolzinaKratki = sc.nextInt(); //d
    int stKratkih = sc.nextInt(); //n
    sc.nextLine(); // prehod v novo vrstico
    char [] Dolgi = sc.nextLine().toCharArray(); //prebrano dolgo zaporedje
    char [][] TabelaKratki = new char [stKratkih][dolzinaKratki];
    int [] results = new int [stKratkih];
    for (int i=0; i<stKratkih; i++) {
        TabelaKratki[i]=sc.nextLine().toCharArray();
    }
    for (int i=0; i<dolzinaDolgi-dolzinaKratki; i++) {
        char [] vmesnoZaporedje = new char [dolzinaKratki];
        vmesnoZaporedje = Arrays.copyOfRange (Dolgi, 0+i, dolzinaKratki+i-1);
        for (int j=0; j<stKratkih; j++) {
            if (TabelaKratki [j] == vmesnoZaporedje) {
                results [j] += 1;
            }
        }
    }
    for (int index = 0; index<stKratkih; index++) {
        System.out.println(results[index]);
    }

}

}

Vid Stropnik
  • 182
  • 10

1 Answers1

1

Perhaps regular expression is much better. 1. Convert the text to be searched into a pattern. 2. Store all different sets of characters into array. 3. Loop the array and loop to find occurrences using the pattern.

Refer to this answer for count the occurrences. java regex match count

Community
  • 1
  • 1
Azman K.
  • 11
  • 1