Write a program to count occurances of each character in a string
-
Here is the function where your get the occurrence of each character in any string with O(n) times.
public static void main(String args[]){
String str="mam is going";
HashMap<String, Integer> freqOfChar=calculateCharFrequency(str!=null?str.trim():"");
printFreeOfChar(freqOfChar);
}static HashMap<String, Integer> calculateCharFrequency(String str){ HashMap<String, Integer> freqOfChar = new HashMap<String, Integer>(); String ch; if(str!=null){ for(int i=0;i<str.length();i++){ ch=Character.toString(str.charAt(i)).trim(); if(ch.length()>0){ if(freqOfChar.get(ch)!=null){ freqOfChar.put(ch, (freqOfChar.get(ch)+1)); }else{ freqOfChar.put(ch, 1); } } } } return freqOfChar; } static void printFreeOfChar(HashMap<String, Integer> freqOfChar){ for (String key : freqOfChar.keySet()) { System.out.println("Char: "+key+ "; Occurance: "+freqOfChar.get(key)); } }
output:
Char: o; Occurance: 1
Char: i; Occurance: 2
Char: m; Occurance: 2
Char: a; Occurance: 1
Char: n; Occurance: 1
Char: g; Occurance: 2
Char: s; Occurance: 1 -
Here is the function where your get the occurrence of each character in any string with O(n) times.
public static void main(String args[]){
String str="mam is going";
HashMap<String, Integer> freqOfChar=calculateCharFrequency(str!=null?str.trim():"");
printFreeOfChar(freqOfChar);
}static HashMap<String, Integer> calculateCharFrequency(String str){ HashMap<String, Integer> freqOfChar = new HashMap<String, Integer>(); String ch; if(str!=null){ for(int i=0;i<str.length();i++){ ch=Character.toString(str.charAt(i)).trim(); if(ch.length()>0){ if(freqOfChar.get(ch)!=null){ freqOfChar.put(ch, (freqOfChar.get(ch)+1)); }else{ freqOfChar.put(ch, 1); } } } } return freqOfChar; } static void printFreeOfChar(HashMap<String, Integer> freqOfChar){ for (String key : freqOfChar.keySet()) { System.out.println("Char: "+key+ "; Occurance: "+freqOfChar.get(key)); } }
output:
Char: o; Occurance: 1
Char: i; Occurance: 2
Char: m; Occurance: 2
Char: a; Occurance: 1
Char: n; Occurance: 1
Char: g; Occurance: 2
Char: s; Occurance: 1 -
The Answer is available on this link http://techgurulab.com/course/java-tutorials/[^]