How to display the word and its number of occurences in a string in C

63 views Asked by At

Basically, I want to display the words and their number of occurrences in a string. It can be both case sensitive and vice-versa.

For e.g if the input string is "Hello World How are you Hello how", the output should be:

Hello,2
World,1
How,2
are,1
you,1

I am not able to figure out the logic for this yet; any help?

2

There are 2 answers

0
Sourav Ghosh On

Use

  1. fgets()
  2. strtok_r()
  3. strcmp()

Check these three APIs. Figure out the code-to-write, implement, run into issues, come back and we'll be here to help.

0
BLUEPIXY On
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>

bool eq(const char *s, const char *w, char ignore_case){
    char si, wi;
    while(*w && !isspace(*w)){
        if(ignore_case != 'n'){
            si = tolower(*s++);
            wi = tolower(*w++);
        } else {
            si = *s++;
            wi = *w++;
        }
        if(si != wi)
            return false;
    }
    return !*s || isspace(*s);
}

char *next_word(char *w){
    while(*w && !isspace(*w))
        ++w;
    if(!*w)
        return w;
    while(isspace(*w))
        ++w;
    return w;
}
int main() {
    char ignore_case = 'n';
    char *word, *str;
    char string[128];

    printf("ignore case ?(y/n):");
    scanf("%c", &ignore_case);

    printf("input string : ");
    scanf(" %127[^\n]", string);

    str = string;
    while(*str){
        int counter = 1;

        word = next_word(str);//skip first word
        while(*word){
            char *p = NULL;
            if(eq(str, word, ignore_case)){
                p = word;
                ++counter;
            }
            word = next_word(word);//move to next word top
            if(p)
                memset(p, ' ', word - p);//clear already match word
        }
        word = str;
        str = next_word(str);
        while(*word && !isspace(*word))
            putchar(*word++);
        printf(",%d\n", counter);
    }
    return 0;
}