-2

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?

4

2 回答 2

2

利用

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

检查这三个 API。找出要编写的代码,实现,遇到问题,回来,我们会在这里提供帮助。

于 2014-11-18T05:46:18.180 回答
0
#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;
}
于 2014-11-18T12:58:02.803 回答