#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
*/