In this program will shown you how to find the frequency of characters in a string using C language.
This program in C language counts the number of occurrences in a text file of all the searched characters.
Example:
Text file contains the text “I am a programmer”.
The searched characters: a, b, c, d, e.
The number of occurrences:
- a:3
- b:3
- c:1
- d:1
- e:5
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
#include <stdio.h> #include <stdlib.h> void search_chars(char characters[],int size) { //open a file in read mode FILE *file = fopen("d:/file.txt","r"); char c; //array that saves repetitions int repetition[size]; //initialize to 0 for(int i = 0 ; i < size; i++) repetition[i]=0; //if the file exists if(file) { // as long as it's not the end of the file // read a character while((c=(char)getc(file))!=EOF) { // The character read is compare with // all characters searched for(int i = 0 ; i < size; i++) { // if he is equal he is incrementing // the counter associated with the character if(c==characters[i]) repetition[i]++; } } //close the file fclose(file); //display printf("Number of repetitions:\n"); for(int i = 0 ; i < size; i++) printf("\t%c : %d\n",characters[i],repetition[i]); } else printf("\aERROR: Can not open file: %s", file); } int main() { char str[]="abcde"; // sizeof (string) -1: size of the array // (-1 to not count the '\ 0') // '\ 0' indicates the end of the array search_chars(str,sizeof(str)-1); system("pause"); } |