【问题标题】:How to count words and punctuation in a string C program?如何计算字符串 C 程序中的单词和标点符号?
【发布时间】:2015-09-13 05:29:33
【问题描述】:

我正在尝试用 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();

    }

【问题讨论】:

  • 那么长的 OR || 序列在 C 中不是正确的语法。

标签: c loops for-loop


【解决方案1】:

一种方法是分别读取每个字符并进行处理。

#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
}

【讨论】:

    【解决方案2】:

    有更多的代码行,但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;
    }
    

    【讨论】:

    • 为什么不从第二个开始分组:case '.': case '?': case '!': case '(': case ')': case '*': case '&amp;': pcount++; break;
    • 好点 - 我写得很快,没有思考 :) 我很久没用 switch 语句了
    猜你喜欢
    • 2012-09-23
    • 1970-01-01
    • 2011-10-21
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    相关资源
    最近更新 更多