Find frequency of a character in String without using loop

By | September 10, 2017

 

This is a program to find the number of occurrences of a character in String without using a loop.
Approach:
We are using replaceAll and length method of Java String Class here to count the number of a particular character in a string.

 

//Write a program to find the number of occurrences of a character in a string without using loop?
package Exercise3;

public class Main {
    public static void main(String[] args) {
        String str = "This is an Example Of The Character";

        System.out.println("Length Of String:" + str.length());
        System.out.println("Length Of String Without a :" + str.replace("a", "").length());
        int charcount = str.length() - str.replaceAll("a", "").length();
        System.out.println("Occurrence Of A Char In String: " + charcount);
    }
}

Output

Length Of String:35
Length Of String Without A:31
Occurrence Of A Char In String: 4