Home Tutorial Java Core Count Characters from the input string Java

 
 

Share on Google+Share on Google+
Count Characters from the input string Java
Posted on: October 24, 2009 at 12:00 AM
Advertisement
In this section, you will learn how to count the occurrence of each character in the string.

Count Characters from the input string of Java

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[] argsthrows 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
Advertisement

Related Tags for Count Characters from the input string Java:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 24, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com