如何生成具有相同字符数的单词数?

时间:2015-11-16 05:06:53

标签: c arrays kernighan-and-ritchie

我正在通过k& r学习c编程语言,我遇到了这个练习“编写一个程序来打印输入中单词长度的直方图。很容易绘制直方图,条形水平;垂直方向更具挑战性“我决定对问题做一点改动,所以这就是我到目前为止所做的:

 #include <stdio.h>
    #define OUT 0
    #define IN 1
    main(){
        int c, nw, nc, i,state,j;
        nw = nc = 0;

        while ((c = getchar()) != EOF){
            if (c == '\n' || c == '\t' || c == ' ')
                state = OUT;
            else if (state == OUT) {
                state = IN;
                ++nw;
            }


    if (state == IN) {
                    if (c >= 'a' && c <= 'z')
    ++nc;
    if ( c >='0' && c<='9')
    ++nc;
            }
        }
        printf("Lengths of words");
        for (j = 1; j < 10; ++j){
                printf("[%d]-%d", j, nw);
        }
     }

所以我希望计算机可以打印出来:

 Lengths of words
    [0]- nw with > 10 characters
    [1]- nw with 1 character
    [2]- nw with 2 characters
    [3]- nw with 3 characters
    ...

例如:my name is linh这就是它打印的内容:

[0]- 0
[1]- 0
[2]- 2
[3]- 0
[4]- 0
...

我知道这个练习是关于数组的,因此,我可能在这个程序中遗漏了它的概念,并且需要有人来纠正我:)我很想知道我怎样才能生成单词的数量相同数量的字符。此外,我希望我的代码能够以某种方式进行审核......我相信它有一些误解。我对C比较陌生,任何有帮助的人都会非常感激:)谢谢你提前!

1 个答案:

答案 0 :(得分:0)

我试图解决你的问题。我希望它会对你有所帮助,这对你来说很简单。

 #include <stdio.h>

typedef int bool;
#define true 1
#define false 0
#define maxNumOfWords 10

char *createHistogram(int n) {
    char *hist = (char *)malloc((n + 1) * sizeof(char));
    if (hist == NULL) {
        return "";
    }
    int i = 0;
    for (i = 0; i < n; i++) {
        hist[i] = '*';
    }
    hist[i] = '\0';
    return hist;
}

int main(int argc, char *argv[]) {
    bool isInWord = false;
    int results[maxNumOfWords];
    int index = -1;
    int j;
    char c;

    // initialize the result array to 0
    for (j = 0; j < maxNumOfWords; j++) {
        results[j] = 0;
    }
    while ((index < maxNumOfWords) && ((c = getchar()) != EOF)) {
        switch (c) {
        case '\n':
        case '\r':
        case '\t':
        case ' ':
            isInWord = false;
            break;
        default:
            // on the beginning of the first word
            if (isInWord == false) {
                ++index;
            }
            isInWord = true;
            if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
                results[index] += 1;
            break;
        }
    }
    printf("Lengths of words:\n");
    for (j = 0; j < maxNumOfWords; j++) {
        int n = results[j];
        printf("[%d]-%d %s\n", j, n, createHistogram(n));
    }
}