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
Can you please change the color of code to white in dark mode?
Its hard to read ..