Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,884 questions

51,810 answers

573 users

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 82 views
1 answer 175 views
1 answer 224 views
1 answer 97 views
1 answer 85 views
1 answer 92 views
...