【问题标题】:Count words in a user-input string in C在 C 中计算用户输入字符串中的单词
【发布时间】:2014-09-09 13:47:30
【问题描述】:

所以,我们在课堂上得到了这个程序。 “用C编写一个程序来计算用户输入的句子中的单词数。” 这是我能想到的,但单词的数量总是比正确的数字少一。我的老师告诉每个人在打印之前将字数加 1。我认为它有一个错误,如果我们不输入任何单词,即按Enter而不是打字,我老师建议的程序仍然会将字数计算为1而不是0。你知道有什么方法可以得到正确的单词计数而不只是在最后加 1? 代码:

我的代码(比正确的少 1):

#include <stdio.h>
#include <string.h>
void main()
{
 char s[200];
 int count = 0, i;
 printf("enter the string\n");
 gets(s);
 for (i = 0;i<strlen(s);i++)
 {
  if (s[i] == ' ')
  count++;    
 }
 printf("number of words in given string are: %d\n", count);
}

【问题讨论】:

  • 如果用户输入两个相邻的空格怎么办? one two
  • 请编译所有警告和调试信息 (gcc -Wall -g)。另外,不要使用gets,而是使用fgets。最后学习现在如何使用调试器
  • 不要使用gets(),而是fgets,你也可以使用\n作为单词分隔符。
  • 阅读isalpha(3) 等... 将Hello, I am ... John-F Kennedy! 视为输入。
  • @BasileStarynkevitch:当然,但他自己尝试一下是个好主意。这个问题充满了怪癖,可以教会他很多东西。使用函数不是一个好主意。

标签: c string counter words


【解决方案1】:

只是你在计算空格,如果用户以一堆空格结束字符串,这也是不正确的。试试这样的:

#include <stdio.h>
#include <string.h>
void main()
{
 char s[200];
 int count = 0, i;
 int foundLetter = False;
 printf("enter the string\n");
 gets(s);
 for (i = 0;i<strlen(s);i++)
 {
  if (s[i] == ' ')
      foundLetter = False;
  else 
  {    
      if (foundLetter == False)
          count++;
      foundLetter = True;
  }
 }
 printf("number of words in given string are: %d\n", count);
}

正如其他用户评论的那样,您的程序容易受到许多其他问题的影响,具体取决于输入的字符串。我发布的示例假定任何不是空格的都是一个字母,如果你找到至少一个字母,那就是一个单词。您可以使用计数器代替布尔值来确保单词至少有一定的长度。您还可以通过编写自己的正则表达式函数或使用现有函数来检查它是否不是数字或符号。正如其他人所说,您可以使用此程序做更多事情,但我提供了一个示例来为您指明正确的方向。

【讨论】:

  • 非常感谢!这正是我想要弄清楚的:)
  • main 应该是 int 而不是 void。 FalseTrue 究竟是什么?
【解决方案2】:

你在计算非单词的数量,但你应该计算单词的数量。

如果一个词被定义为一个或多个字母的序列,你的代码可能是:

for every character in the string
  if the character is part of a word ( "the car's wheel" is three words )
    increase the word count
    while the character is part of a word, increment your pointer 

【讨论】:

  • +1 你一针见血:“你在计算非单词的数量”
【解决方案3】:

一项改进是处理在单词或制表符之间包含多个空格的行,同时仍将简单的 return '\n' 视为一个单词。使用getline 提供了许多优势,包括提供读取的字符数。这是该方法的一个示例:

编辑逻辑简化:

#include <stdio.h>

int main (void) {

    char *line = NULL;  /* pointer to use with getline ()  */
    char *p = NULL;     /* pointer to parse getline return */
    ssize_t read = 0;
    size_t n = 0;
    int spaces = 0;     /* counter for spaces and newlines */
    int total = 0;      /* counter for total words read    */

    printf ("\nEnter a line of text (or ctrl+d to quit)\n\n");

    while (printf (" input: ") && (read = getline (&line, &n, stdin)) != -1) {

        spaces = 0;
        p = line;

        if (read > 1) {         /* read = 1 covers '\n' case (blank line with [enter]) */
            while (*p) {                            /* for each character in line      */
                if (*p == '\t' || *p == ' ') {      /* if space,       */
                    while (*p == '\t' || *p == ' ') /* read all spaces */
                        p++;
                    spaces += 1;                    /* consider sequence of spaces 1   */
                } else
                    p++;                            /* if not space, increment pointer */
            }
        }

        total += spaces + 1;  /* words in line = spaces + 1 */
        printf (" chars read: %2zd,  spaces: %2d  total: %3d  line: %s\n", 
                read, spaces, total, (read > 1) ? line : "[enter]\n");
    }

    printf ("\n\n  Total words read: %d\n\n", total);

    return 0;

}

输出:

Enter a line of text (or ctrl+d to quit)

input: my
chars read:  3,  spaces:  0  total:   1  line: my

input: dog has
chars read:  8,  spaces:  1  total:   3  line: dog has

input: fleas   and  ticks
chars read: 17,  spaces:  2  total:   6  line: fleas   and  ticks

input:
chars read:  1,  spaces:  0  total:   7  line: [enter]

input:
chars read:  1,  spaces:  0  total:   8  line: [enter]

input: total_words   10
chars read: 17,  spaces:  1  total:  10  line: total_words   10

input:

  Total words read: 10

【讨论】:

  • 关于这一行: if (*p != '\t' || *p != ' ') { *p 不能同时是两个条件,所以这行将始终为真
  • 不错,应该是&amp;&amp;
【解决方案4】:
//input should be alphanumeric sentences only
#include <bits/stdc++.h>
using namespace std;

int main()
{
    freopen("count_words_input.txt","r",stdin); // input file
    char c;
    long long i,wcount=0,f=0;
    i=0;
    while(scanf("%c",&c) == 1)
    {
        if(c == ' ' || c == '\n' || c == '\t' || c == '.')
         f=0;
        else if(f == 0)
            {
            wcount++;
            f=1;
             }
     }

    printf("%lld\n",wcount);
    return 0;
}

【讨论】:

    猜你喜欢
    • 2022-08-02
    • 2021-10-07
    • 2020-08-08
    • 1970-01-01
    • 2012-09-23
    • 2023-03-21
    相关资源
    最近更新 更多