settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Count Substring Occurrences in Java

+6 votes

Write a program to find how many times given string appears in given text as substring. The text is given at the first input line. The search string is given at the second input line. The output is an integer number. Please ignore the character casing.

Examples:

Java task Count Substring Occurrences

asked in Java category by user hues
edited by user golearnweb

2 Answers

+3 votes
 
Best answer

Here's my solution  - please NOTE: IT WILL NOT WORK FOR ALL THE EXAMPLES!

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

        String array = scanner.nextLine().toLowerCase();
        String toCompare = scanner.nextLine().toLowerCase();

        Pattern pattern = Pattern.compile(toCompare);
        Matcher matcher = pattern.matcher(array);

        int count = 0;

        while(matcher.find()){
            count++;
        }
        System.out.println(count);
    }
}
answered by user john7
edited by user golearnweb
+2 votes

Here's my solution - but it will also NOT work for the aaaaa example - cannot manage to find a solution for it...

import java.util.Scanner;

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

        String[] array = scanner.nextLine().toLowerCase().split("[\\s]+");
        String toCompare = scanner.nextLine().toLowerCase();

//        for (int i = 0; i < array.length; i++) {
//            System.out.println(array[i]);
//        }

        int count = 0;

        for (int i = 0; i < array.length; i++) {
            if (array[i].contains(toCompare)) {
                count++;
            }
        }
        System.out.println(count);
    }
}
answered by user richard8502
edited by user golearnweb
...