Java Program to Count Frequency of Character in String ( 4 Methods )

By | 16.03.2017

Java Program to Count Frequency of Character in String


Write a Java Program to Count Frequency of Character in String. Here’s a Simple Program To Count Frequency of Character in String in Java Programming Language.

Since there’s no pre-build function present in Java for calculating the occurrence of the characters or alphabets. Hence we need to implement our own logic to Count Frequency of Character in a String. Here we will see four different methods of solving the problem.


What are Strings?


String is basically a sequence of Characters. String is a Class provided in Java Library Files which are used to manipulate the Strings. In C Programming, String was an Array of Characters but here the case is bit different.


ALGORITHM :


1. Start

2. Accept a string from the user.

3.Accept a character from the user which u want to search.

4. Count the no. of times it occurs in the string.

5. Print its frequency.

6. End


Following Java Program ask to the user to enter a string and character to find the frequency of character present in the string and display the frequency of character on the screen.

Below is the source code for Java Program to Count no of occurrences of Character in String which is successfully compiled and run on Windows System to produce desired output as shown below :


1. Using replaceAll( ) and length( ) in Strings(Java) :


SOURCE CODE  : : 


2. Using Simple for loop in Java : :


SOURCE CODE : :


import java.util.Scanner;
public class Count_Occurrance {

     public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter any String : ");
        String s = sc.next().toLowerCase();
        System.out.print("Enter a character to count in [" + s + "] : ");
        char c = sc.next(".").toLowerCase().charAt(0);
        int cn = 0;
        for (int i = 0; i < s.length(); i++) {
            if (c == s.charAt(i)) {
                cn++;
            }
        }
        System.out.println(c + " occurs " + cn + " times in " + s);
        sc.close();
    }
}

OUTPUT : :


Enter any String : CodezClub
Enter a character to count in [codezclub] : o
o occurs 1 times in codezclub

 


3. Using Enhanced for loop in String(Java): :


4. Using Recursion in Java : :


5 1 vote
Article Rating
Category: Java Programming String Programs Tags:

About Tunde A

My name is Tunde Ajetomobi, a Tech Enthusiast and Growth Hacker. I enjoy creating helpful content that solves problem across different topics. Codezclub is my way of helping young aspiring programmers and students to hone their skills and find solutions on fundamental programming languages.

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
PRIYANSHI PANDYA

Can you please change the color of code to white in dark mode?
Its hard to read ..