Tuesday, 20 September 2016

Java Program to Count Numbers of Characters From String ?

Previously we have discussed the Program for 
Java program take array as input and count element occurrence and then find element with maximum occurrence ?

This program is for counting the number of characters from string , In this program we are using Map<K,V> and Set<K> Interface to solve this problem.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class CountNumberOfCharacters {

 public static void main(String[] args) {
   String s1="abcb";
   Map<Character, Integer> map=new HashMap<>();
   for(int i=0;i<s1.length();i++){
    char ch=s1.charAt(i);
     if(map.containsKey(ch)){
      map.put(ch, map.get(ch)+1);
     }
     else{
      map.put(ch, 1);
     }
   }
   Set<Character> set=map.keySet();
   for(Character c:set){
    System.out.println("CHARACTER = "+c+" , OCCURENCE = "+map.get(c));
   }
 }

} 

Output :-

CHARACTER = a , OCCURENCE = 1
CHARACTER = b , OCCURENCE = 2

CHARACTER = c , OCCURENCE = 1

No comments:

Post a Comment