w3resource

Java: Counts occurrences of a certain character in a given string

Java String: Exercise-107 with Solution

Write a Java program to count occurrences of a certain character in a given string.

Sample Solution:

Main.java Code:

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

public class Main {

    private static final String TEXT = "My high school, the Illinois Mathematics and Science Academy, "
            + "showed me that anything is possible and that you're never too young to think big. "
            + "At 15, I worked as a computer programmer at the Fermi National Accelerator Laboratory, "
            + "or Fermilab. After graduating, I attended Stanford for a degree in economics and "
            + "computer science.";
    private static final char CHAR_TO_COUNT = 'u';

    private static final String TEXT_CP = "😍 I love 💕 you Ӝ so much 💕 😍";
    private static final String CHAR_TO_COUNT_CP = "Ӝ";   // Unicode: \u04DC, Code Point: 1244
    private static final String CHAR_TO_COUNT_CPS = "💕"; // Unicode: \uD83D\uDC95, Code Point: 128149

    public static void main(String[] args) {
        System.out.println("Input text: \n" + TEXT + "\n");

        System.out.println("\n\nASCII or 16 bits Unicode characters (less than 65,535 (0xFFFF)) examples:\n");

        System.out.println("replace() based solution:");
        long startTimeV1 = System.nanoTime();

        int countV1 = Strings
                .countOccurrencesOfACertainCharacterV1(TEXT, CHAR_TO_COUNT);

        displayExecutionTime(System.nanoTime() - startTimeV1);
        System.out.println("Character '" + CHAR_TO_COUNT + "' occured " + countV1 + " time(s)");

        System.out.println();
        System.out.println("charAt() based solution:");
        long startTimeV2 = System.nanoTime();

        int countV2 = Strings
                .countOccurrencesOfACertainCharacterV2(TEXT, CHAR_TO_COUNT);

        displayExecutionTime(System.nanoTime() - startTimeV2);
        System.out.println("Character '" + CHAR_TO_COUNT + "' occured " + countV2 + " time(s)");

        System.out.println();
        System.out.println("Java 8, functional-style solution:");
        long startTimeV3 = System.nanoTime();

        long countV3 = Strings
                .countOccurrencesOfACertainCharacterV3(TEXT, CHAR_TO_COUNT);

        displayExecutionTime(System.nanoTime() - startTimeV3);
        System.out.println("Character '" + CHAR_TO_COUNT + "' occured " + countV3 + " time(s)");

        System.out.println("\n--------------------------------------\n");
        
        System.out.println("Input text: \n" + TEXT_CP + "\n");
        
        System.out.println("\n\nIncluding Unicode surrogate pairs examples:\n");

        System.out.println("replace() based solution:");
        long startTimeV4 = System.nanoTime();

        int countV4 = Strings
                .countOccurrencesOfACertainCharacterVCP1(TEXT_CP, CHAR_TO_COUNT_CP);

        displayExecutionTime(System.nanoTime() - startTimeV4);
        System.out.println("Character '" + CHAR_TO_COUNT_CP + "' occured " + countV4 + " time(s)");

        System.out.println();
        System.out.println("replace() based solution:");
        long startTimeV5 = System.nanoTime();

        int countV5 = Strings
                .countOccurrencesOfACertainCharacterVCP1(TEXT_CP, CHAR_TO_COUNT_CPS);

        displayExecutionTime(System.nanoTime() - startTimeV5);
        System.out.println("Character '" + CHAR_TO_COUNT_CPS + "' occured " + countV5 + " time(s)");

        System.out.println();
        System.out.println("codePointAt() based solution:");
        long startTimeV6 = System.nanoTime();

        int countV6 = Strings
                .countOccurrencesOfACertainCharacterVCP2(TEXT_CP, CHAR_TO_COUNT_CP);

        displayExecutionTime(System.nanoTime() - startTimeV6);
        System.out.println("Character '" + CHAR_TO_COUNT_CP + "' occured " + countV6 + " time(s)");

        System.out.println();
        System.out.println("codePointAt() based solution:");
        long startTimeV7 = System.nanoTime();

        int countV7 = Strings
                .countOccurrencesOfACertainCharacterVCP2(TEXT_CP, CHAR_TO_COUNT_CPS);

        displayExecutionTime(System.nanoTime() - startTimeV7);
        System.out.println("Character '" + CHAR_TO_COUNT_CPS + "' occured " + countV7 + " time(s)");

        System.out.println();
        System.out.println("Java 8, functional-style solution:");
        long startTimeV8 = System.nanoTime();

        long countV8 = Strings
                .countOccurrencesOfACertainCharacterVCP3(TEXT_CP, CHAR_TO_COUNT_CP);

        displayExecutionTime(System.nanoTime() - startTimeV8);
        System.out.println("Character '" + CHAR_TO_COUNT_CP + "' occured " + countV8 + " time(s)");

        System.out.println();
        System.out.println("Java 8, functional-style solution:");
        long startTimeV9 = System.nanoTime();

        long countV9 = Strings
                .countOccurrencesOfACertainCharacterVCP3(TEXT_CP, CHAR_TO_COUNT_CPS);

        displayExecutionTime(System.nanoTime() - startTimeV9);
        System.out.println("Character '" + CHAR_TO_COUNT_CPS + "' occured " + countV9 + " time(s)");
    }

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

Strings.java Code:

//MIT License: https://bit.ly/35gZLa3
public final class Strings {

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

    public static int countOccurrencesOfACertainCharacterV1(String str, char ch) {

        if (str == null || str.isEmpty()) {
            // or throw IllegalArgumentException            
            return -1;
        }

        return str.length() - str.replace(String.valueOf(ch), "").length();
    }

    public static int countOccurrencesOfACertainCharacterVCP1(String str, String ch) {

        if (str == null || ch == null || str.isEmpty() || ch.isEmpty()) {
            // or throw IllegalArgumentException            
            return -1;
        }

        if (ch.codePointCount(0, ch.length()) > 1) {
            return -1; // there is more than 1 Unicode character in the given String
        }

        int result = str.length() - str.replace(ch, "").length();

        // if ch.length() return 2 then this is a Unicode surrogate pair
        return ch.length() == 2 ? result / 2 : result;
    }

    public static int countOccurrencesOfACertainCharacterV2(String str, char ch) {

        if (str == null || str.isEmpty()) {
            // or throw IllegalArgumentException
            return -1;
        }

        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == ch) {
                count++;
            }
        }
        return count;
    }

    public static int countOccurrencesOfACertainCharacterVCP2(String str, String ch) {

        if (str == null || ch == null || str.isEmpty() || ch.isEmpty()) {
            // or throw IllegalArgumentException            
            return -1;
        }

        if (ch.codePointCount(0, ch.length()) > 1) {
            return -1; // there is more than 1 Unicode character in the given String
        }

        int count = 0;
        int codePoint = ch.codePointAt(0);
        for (int i = 0; i < str.length(); i++) {
            if (str.codePointAt(i) == codePoint) {
                count++;
            }
        }

        return count;
    }

    public static long countOccurrencesOfACertainCharacterV3(String str, char ch) {

        if (str == null || str.isEmpty()) {
            // or throw IllegalArgumentException
            return -1;
        }

        return str.chars()
                .filter(c -> c == ch)
                .count();
    }
    
    public static long countOccurrencesOfACertainCharacterVCP3(String str, String ch) {

        if (str == null || ch == null || str.isEmpty() || ch.isEmpty()) {
            // or throw IllegalArgumentException            
            return -1;
        }

        if (ch.codePointCount(0, ch.length()) > 1) {
            return -1; // there is more than 1 Unicode character in the given String
        }

        int codePoint = ch.codePointAt(0);        
        
        return str.codePoints()
                .filter(c -> c == codePoint)
                .count();
    }
}

Sample Output:

Input text: 
My high school, the Illinois Mathematics and Science Academy, showed me that anything is possible and that you're never too young to think big. At 15, I worked as a computer programmer at the Fermi National Accelerator Laboratory, or Fermilab. After graduating, I attended Stanford for a degree in economics and computer science.



ASCII or 16 bits Unicode characters (less than 65,535 (0xFFFF)) examples:

replace() based solution:
Execution time: 2451480 ns (2 ms)
Character 'u' occured 5 time(s)

charAt() based solution:
Execution time: 40343 ns (0 ms)
Character 'u' occured 5 time(s)

Java 8, functional-style solution:
Execution time: 156518104 ns (156 ms)
Character 'u' occured 5 time(s)

--------------------------------------

Input text: 
😍 I love 💕 you Ӝ so much 💕 😍



Including Unicode surrogate pairs examples:

replace() based solution:
Execution time: 97920 ns (0 ms)
Character 'Ӝ' occured 1 time(s)

replace() based solution:
Execution time: 403313 ns (0 ms)
Character '💕' occured 2 time(s)

codePointAt() based solution:
Execution time: 31224 ns (0 ms)
Character 'Ӝ' occured 1 time(s)

codePointAt() based solution:
Execution time: 25059 ns (0 ms)
Character '💕' occured 2 time(s)

Java 8, functional-style solution:
Execution time: 1735086 ns (1 ms)
Character 'Ӝ' occured 1 time(s)

Java 8, functional-style solution:
Execution time: 41650 ns (0 ms)
Character '💕' occured 2 time(s)

Flowchart:

Flowchart: Java String Exercises - Count Occurrences Of Character
Flowchart: Java String Exercises - Count Occurrences Of Character

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous Java Exercise: Concatenate a given string with itself of a given number of times.
Next Java Exercise: Check two consecutive, identical letters in a given string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/java-exercises/string/java-string-exercise-107.php