C语言 在 C 中计算用户输入字符串中的单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25746334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:21:15  来源:igfitidea点击:

Count words in a user-input string in C

cstringcounterwords

提问by Vasundhara Mehta

So, we were given this program in class. "Write a Program in C to count the number of words in a sentence input by the user." This is what i could come up with, but the number of words is always one less than what is the correct number. My teacher told everyone to just add 1 to the word count before printing it. I think it has a bug, if we don't enter any words, i.e. , press Enter instead of typing,the program suggested by my teacher would still give word count as 1 not 0. Do you know of any way to get proper word count without just adding 1 at the end? Code:

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

My code(giving 1 less than correct) :

我的代码(给 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);
}

采纳答案by Optox

It's just that you're counting spaces, this would also be incorrect if the user ended the string with a bunch of spaces. Try something like this:

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

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

As other users have commented, your program is susceptible to many other issues depending on the string inputed. The example I have posted assumes that anything that is not a space is a letter and if you find at least one letter, than that's a word. Instead of boolean values you could use a counter to make sure that the word is at least a certain length. You could also check to see that it is not a number or symbol by either writing your own regex function or using an existing one. As others have said there is a lot more you can do with this program, but I've provided an example to point you in the right direction.

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

回答by Carl

You are counting the amount of non-words, but you should be counting the amount of words.

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

If a word is defined as a sequence of one or more letters, your code might go as:

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

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 

回答by David C. Rankin

One improvement would be to handle lines that contain multiple spaces between words or tabs, while still considering a simple return '\n'as a word. Using getlineprovides a number of advantages including providing the number of characters read. Here is an example of the approach:

一种改进是处理在单词或制表符之间包含多个空格的行,同时仍将简单的返回'\n'视为单词。Usinggetline提供了许多优点,包括提供读取的字符数。以下是该方法的示例:

Editlogic simplified:

编辑逻辑简化:

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

}

output:

输出:

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

回答by Jemas Kumar

//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;
}