I need to write some kind of loop that can count the frequency of each letter in a string.
For example: "aasjjikkk" would count 2 'a', 1 's', 2 'j', 1 'i', 3 'k'. Ultimately id like these to end up in a map with the character as the key and the count as the value. Any good idea how to do this?
Algorithm to find the frequency of characters in a string Input the string from the user. Traverse the string, character by character and store the count of each of the characters in an array. Print the array that contains the frequency of all the characters.
The code snippet for this is given as follows. for(int i = 0; str[i] != '\0'; i++) { if(str[i] == c) count++; } cout<<"Frequency of alphabet "<<c<<" in the string is "<<count; The program to find the frequency of all the alphabets in the string is given as follows.
count() coupled with set() can also achieve this task, in this we just iterate over the set converted string and get the count of each character in original string and assign that element with that value counted using count() .
A string is a one-dimensional character array that is terminated by a null character. Frequency of characters in a string is the number of times they occur in a string. A program to find the frequency of a particular alphabet is given as follows. Example.
Initialize an array freq [] to store the frequency of each alphabet in the given string. The 0th index stores the frequency of the character ‘ a’, 1 st/sup> index stores the frequency of the character ‘b’ and so on. Iterate over the given string S and increment the frequency of each character encountered by 1, by performing freq [S [i] – ‘a’] += 1.
In the above program, for loop is used to find the frequency of alphabet a for the string given. In the for loop, if str [i] is equal to the alphabet, then count is incremented by 1.
The 0th index stores the frequency of the character ‘ a’, 1 st/sup> index stores the frequency of the character ‘b’ and so on. Iterate over the given string S and increment the frequency of each character encountered by 1, by performing freq [S [i] – ‘a’] += 1.
You can use a java Map and map a char
to an int
. You can then iterate over the characters in the string and check if they have been added to the map, if they have, you can then increment its value.
For example:
HashMap<Character, Integer> map = new HashMap<Character, Integer>(); String s = "aasjjikkk"; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); Integer val = map.get(c); if (val != null) { map.put(c, new Integer(val + 1)); } else { map.put(c, 1); } }
At the end you will have a count of all the characters you encountered and you can extract their frequencies from that.
Alternatively, you can use Bozho's solution of using a Multiset and counting the total occurences.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With