Home > front end >  Java String Task
Java String Task

Time:11-05

I have such a problem, I wrote the code and it is almost correct, but it incorrectly considers the situation when in the String "qqqqqqqqqqqqqqqqfunfunfwewewewewewqwyeqet" I need to find the positions and number of occurrences of the string "funf".

import java.util.Scanner;

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

        String s = scan.nextLine();
        String s1 = scan.nextLine();

        Main main = new Main();
        int howManyTimes = main.calculation(s, s1);
        System.out.println(howManyTimes);

        int position = -1;
        while ((position = findNextWordPosition(s, s1, position   1)) != -1) {
            System.out.println(position   1);
        }
    }

    public int calculation(String s, String s1) {

        int howManyTimes = 0;
        for (int i = 0; i < s.length() - s1.length()   1; i  ) {
            int counter = 0;
            for (int j = 0; j < s1.length() && s1.charAt(j) == s.charAt(i j); j  ) {
                counter  ;
            }
            if (s1.length() == counter) {
                howManyTimes  ;
            }
        }
        return howManyTimes;
    }
    static int findNextWordPosition(String s, String s1, int startIndex) {
        if (s.isEmpty() || s1.isEmpty() || startIndex < 0) {
            return -1;
        }

        int position = s.indexOf(s1, startIndex);

        return position;
    }
}

My code handles this situation incorrectly, please help.

CodePudding user response:

'... I need to find the positions and number of occurrences of the string "funf". ...'

Utilize the String#indexOf method.

Here is an example.

List<Integer> l = new ArrayList<>();
int i = -1;
while ((i = s.indexOf("funf",   i)) != -1) l.add(i);

CodePudding user response:

You don't state this explicitly, but from the expected output it's clear that each input character can only contribute to a match once, i.e. funfunf only includes one instance of funf, rather than the two possible instances if input characters can be "reused".

The required fix in your code is to increment the outer loop variable i by the length of the search string when you find a match.

In the calculation method:

if (s1.length() == counter) {
    howManyTimes  ;
    i  = s1.length();
}

You need to do the same in the main method where you're printing the index of a match.

while ((position = findNextWordPosition(s, s1, position   1)) != -1) {
    System.out.println(position   1);
    position  = s1.length();
}

With these changes you get the required output from your code: 1 17

  • Related