How can I perform frequency analysis of a string without using a switch

I work in a school project to implement a Huffman code for a text. The first part of the course requires a frequency analysis of the text. Is there a better way than a giant switch and an array of counters to do this?

t

int[] counters for(int i = 0; i <inString.length(); i++) { switch(inString[i]) case 'A': counters[0]++; . . . 

I would like to make all the alphanumeric characters and punctuation marks. I am using C ++.

+4
source share
3 answers

Why not:

 int counters[256] = {0}; for(int i = 0; i <inString.length(); i++) counters[inString[i]]++; } std::cout << "Count occurences of \'a\'" << counters['a'] << std::endl; 
+8
source

You can use an array indexed by character:

 int counters[256]; for (int i = 0; i < inString.length(); i++) { counters[(unsigned char)inString[i]]++; } 

You will also want to initialize the counters array to zero, of course.

+6
source

using a map seems to be quite applicable:

 map<char,int> chcount; for(int i=0; i<inString.length(); i++){ t=inString[i]; chcount[i]? chcount[i]++ : chcount[i]=1; } 
+2
source

Source: https://habr.com/ru/post/1302641/


All Articles