如何计算字符串C程序中的单词和标点符号?

时间:2015-09-13 05:29:34

标签: c loops for-loop

我正在尝试用C编写一个程序,它计算字符串中的单词和标点符号的数量,而不使用数组等内置函数。没有阵列可以这么做吗?此外,我当前的程序是在下面,并给我一个错误来初始化* word,但我试图让用户输入一个字符串,程序计算它,所以我不想初始化。非常感谢帮助!

    #include <stdio.h>
    #include<conio.h>

    int main(){
        char *word;
        int countword = 0, i;
        int countpunct = 0, i;
        printf("\nEnter the String: ");
        gets(word);
        for (i = 0; word[i] == ' '; i++){
            countword++;
        }
        for (i = 0; word[i] == '.' || '?' || '!' || '(' || ')' || '*' || '&'){
            countpunct++;
        }
        printf("\nThe number of words is %d.", countword);
        printf("\nThe number of punctuation marsks is %d.", countpunct);
        getch();

    }

2 个答案:

答案 0 :(得分:2)

一种方法是分别阅读每个字符并处理它。

#include <stdio.h>
#if 0
#include<conio.h>
#endif

int main(){
    int word;
    int countword = 0;
    int countpunct = 0;
    printf("\nEnter the String: ");
    while ((word = getchar()) != EOF && word != '\n'){
        if (word == ' ') countword++;
        if (word == '.' || word == '?' ||  word == '!' ||  word == '(' ||  word == ')' ||  word == '*' ||  word == '&'){
            countpunct++;
        }
    }
    printf("\nThe number of words is %d.", countword);
    printf("\nThe number of punctuation marsks is %d.", countpunct);
#if 0
    getch();
#endif
}

答案 1 :(得分:1)

还有更多代码行,但switch语句不是一个糟糕的方法。以下代码的一般概念应该有效

#include <stdio.h>
#include <string.h> //for strlen()

int main(){
    char input[255];
    int wcount, pcount, i;
    wcount = pcount = 0;

    printf("\nEnter the String: ");
    fgets(input, 255, stdin);  //use this instead

    for (i=0; i < strlen(input); i++){
        switch (input[i]){
            case ' ':
                if (i > 0) wcount++;
                break;
            case '.':
            case '?':
            case '!':
            case '(':
            case ')':
            case '*':
            case '&':
                pcount++;
                break;
        }
    }
    return 0;
}