[Solved] Count Substring Occurrences in Java

  

4
Topic starter

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

2 Answers
3

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);
    }
}
2

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);
    }
}
Share: