How to count the occurrences of each word in a string with C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
  
#define LEN 20
#define TOTALWORDS 300
  
int countOccurrences(char s[], char words[][LEN], int count[]) {
    int wordindex = 0;
    char word[20] = "";
     
    char *token = strtok(s, " ");
    int i = 0;
    while (token != NULL) {
        int i;
        int notInArray = 1;
        for (i = 0; i < wordindex && notInArray; i++) {
            if (strcmp(words[i], token) == 0) {
                notInArray = 0;
            }
        }
        if (notInArray) {
            strcpy(words[wordindex], token);
            count[wordindex]++;
            wordindex++;
        }
        else {
            count[i - 1]++;
        }
        token = strtok(NULL, " ");
    }
 
    return wordindex; // totalwords
}
      
int main()
{
    char words[TOTALWORDS][LEN] = {"", ""};
    int count[TOTALWORDS] = { 0 };
    char s[] = "c c++ c java c c++ python c# c# php c++ java ruby c";
 
    puts("\n");
      
    int totalwords = countOccurrences(s, words, count);
      
    for (int i = 0; i <  totalwords; i++) {
       printf("%s: %d times\n", words[i], count[i]);
    }    
          
    return 0;
}
         
           
           
           
/*
run:
           
c: 4 times
c++: 3 times
java: 2 times
python: 1 times
c#: 2 times
php: 1 times
ruby: 1 times
        
*/

 



answered Jan 24, 2021 by avibootz
edited Jan 24, 2021 by avibootz

Related questions

1 answer 109 views
1 answer 200 views
1 answer 252 views
1 answer 128 views
1 answer 101 views
1 answer 110 views
1 answer 131 views
...