w3resource

Java String Exercises: Count the occurrences of a given string in another given string

Java String: Exercise-105 with Solution

Write a Java program to count the occurrences of a given string in another given string.

Sample Solution:

Java Code:

import java.util.Arrays;
public class Main {    
    public static void main(String[] args) {
        String main_string = "abcd abc aabc baa abcaa";
       String sub_string = "aa";
       int countV1 = count_sub_str_in_main_str(main_string, sub_string);
       System.out.println(sub_string + "' has occured " + countV1 + " times in '" + main_string + "'");            
   }
  public static int count_sub_str_in_main_str(String main_string, String sub_string) {
       if (main_string == null || sub_string == null) {
           throw new IllegalArgumentException("The given strings cannot be null");
       }
       if (main_string.isEmpty() || sub_string.isEmpty()) {
           return 0;
       }
       int position = 0;
       int ctr = 0;
       int n = sub_string.length();
       while ((position = main_string.indexOf(sub_string, position)) != -1) {
           position = position + n;
           ctr++;
       }
       return ctr;
   }
}

Sample Output:

aa' has occured 3 times in 'abcd abc aabc baa abcaa'

Pictorial Presentation:

Java String Exercises: Count the occurrences of a given string in another given string

Flowchart:

Flowchart: Java String Exercises - Count the occurrences of a given string in another given string.

Count string in another string.

Main.java Code:

//MIT License: https://bit.ly/35gZLa3
import java.time.Clock;
import java.util.concurrent.TimeUnit;

public class Main {

    private static final String STRING = "111111";
    private static final String SUBSTRING = "11";

    public static void main(String[] args) {

        Clock clock = Clock.systemUTC();
        long startTimeV1 = clock.millis();
        int countV1 = Strings.countStringInStringV1(STRING, SUBSTRING);
        displayExecutionTime(clock.millis() - startTimeV1);
        System.out.println("V1: '" + SUBSTRING + "' has occured " + countV1 + " times in '" + STRING + "'");

        long startTimeV2 = clock.millis();
        int countV2 = Strings.countStringInStringV2(STRING, SUBSTRING);
        displayExecutionTime(clock.millis() - startTimeV2);
        System.out.println("V2: '" + SUBSTRING + "' has occured " + countV2 + " times in '" + STRING + "'");

        long startTimeV3 = clock.millis();
        int countV3 = Strings.countStringInStringV3(STRING, SUBSTRING);
        displayExecutionTime(clock.millis() - startTimeV3);
        System.out.println("V3: '" + SUBSTRING + "' has occured " + countV3 + " times in '" + STRING + "'");
    }

    private static void displayExecutionTime(long time) {
        System.out.println("Execution time: " + time + " ms" + " ("
                + TimeUnit.SECONDS.convert(time, TimeUnit.MILLISECONDS) + " s)");
    }

}

Strings.java Code:

//MIT License: https://bit.ly/35gZLa3
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class Strings {

    private Strings() {
        throw new AssertionError("Cannot be instantiated");
    }

    public static int countStringInStringV1(String string, String toFind) {

        if (string == null || toFind == null) {
            throw new IllegalArgumentException("The given strings cannot be null");
        }

        if (string.isEmpty() || toFind.isEmpty()) {
            return 0;
        }

        int position = 0;
        int count = 0;
        int n = toFind.length();

        while ((position = string.indexOf(toFind, position)) != -1) {
            position = position + n;
            count++;
        }

        return count;
    }

    public static int countStringInStringV2(String string, String toFind) {

        if (string == null || toFind == null) {
            throw new IllegalArgumentException("The given strings cannot be null");
        }

        if (string.isEmpty() || toFind.isEmpty()) {
            return 0;
        }

        return string.split(Pattern.quote(toFind), -1).length - 1;
    }

    public static int countStringInStringV3(String string, String toFind) {

        if (string == null || toFind == null) {
            throw new IllegalArgumentException("The given strings cannot be null");
        }

        if (string.isEmpty() || toFind.isEmpty()) {
            return 0;
        }

        Pattern pattern = Pattern.compile(Pattern.quote(toFind));
        Matcher matcher = pattern.matcher(string);

        int position = 0;
        int count = 0;
        while (matcher.find(position)) {           
            position = matcher.start() + 1;
            count++;
        }

        return count;
    }
}

Sample Output:

Execution time: 1 ms (0 s)
V1: '11' has occured 3 times in '111111'
Execution time: 2 ms (0 s)
V2: '11' has occured 3 times in '111111'
Execution time: 1 ms (0 s)
V3: '11' has occured 5 times in '111111'

Flowchart:

Flowchart: Java String Exercises - Count string in another string.
Flowchart: Java String Exercises - Count string in another string.

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to sort in ascending and descending order by length of the given array of strings.
Next: Write a Java program to concatenate a given string with itself of a given number of times.

What is the difficulty level of this exercise?



Java: Tips of the Day

Array vs ArrayLists:

The main difference between these two is that an Array is of fixed size so once you have created an Array you cannot change it but the ArrayList is not of fixed size. You can create instances of ArrayLists without specifying its size. So if you create such instances of an ArrayList without specifying its size Java will create an instance of an ArrayList of default size.

Once an ArrayList is full it re-sizes itself. In fact, an ArrayList is internally supported by an array. So when an ArrayList is resized it will slow down its performance a bit as the contents of the old Array must be copied to a new Array.

At the same time, it's compulsory to specify the size of an Array directly or indirectly while creating it. And also Arrays can store both primitives and objects while ArrayLists only can store objects.

Ref: https://bit.ly/3o8L2KH