In this section, you will learn how to count the occurrence of each character in the string.
In this section, you will learn how to count the occurrence of each character in the string.In this section, you will learn how to count the occurrence of each character in the string. For this, we have prompted the user input the string. The BufferedReader class read the string from the console. Firstly we have removed all the spaces between the string using replaceAll() method and then convert it into character array in order to count the occurrence of each character of the array.
Here is the code of CountCharacters.java
import java.io.*; import java.util.*; class CountCharacters { public static void main(String[] args) throws Exception{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Please enter string "); System.out.println(); String str=br.readLine(); String st=str.replaceAll(" ", ""); char[]third =st.toCharArray(); for(int counter =0;counter<third.length;counter++){ char ch= third[counter]; int count=0; for ( int i=0; i<third.length; i++){ if (ch==third[i]) count++; } boolean flag=false; for(int j=counter-1;j>=0;j--){ if(ch==third[j]) flag=true; } if(!flag){ System.out.println("Character :"+ch+" occurs "+count+" times "); } } } } |
Output:
Please enter string Hello World Character :H occurs 1 times Character :e occurs 1 times Character :l occurs 3 times Character :o occurs 2 times Character :W occurs 1 times Character :r occurs 1 times Character :d occurs 1 times |