my code

Counts of all the words in a sentence.

Snippet options

Download: Download snippet as word_count.c.
Copy snippet: For this you need a free my code account.
Embed code : You will find the embed code for this snippet at the end of the page, if you want to embed it into a website or a blog!


int main(){

        char a[100000],*tokens_all[100000];
        int tok_cnt = 0,flag = 0;

        scanf("%[^\n]%*c",a); // to end string reading when \n is encountered and not at white spaces.
        char *token = strtok(a," "); // strtok return "I" here in the example "I go to Bangalore to night".
        while(token != NULL){
                tokens_all[h++] = token;
                token = strtok(NULL," "); // strtok return "go" in the first iteration and the next word in the next iteration for "I go to Bangalore to night".
        for(int i=0;i<tok_cnt;i++){
                int cnt = 1; // as the word is present at least once.
                for(int j=0;j<tok_cnt;j++){
                        if(j < i){
                                if(strcmp(tokens_all[i],tokens_all[j]) == 0){ // If the word was already encountered, in which case the count of the word has already been calculated.
                                        flag = 1;
                        else if(j != i){
                                if(strcmp(tokens_all[i],tokens_all[j]) == 0) cnt++; // for getting the count of the word in the sentence.

                if(flag == 1){ // if the word was previously encountered.
                        flag = 0;
                        printf("%s: %d\n",tokens_all[i],cnt);

        return 0;

Create a free my code account now.

my code is a free service, which allows you to save and manage code snippes of any kind and programming language. We provide many advantages for your daily work with code-snippets, also for your teamwork. Give it a try!

Find out more and register now

You can customize the height of iFrame-Codes as needed! You can find more infos in our API Reference for iframe Embeds.