计算C中用户输入字符串中的单词 [英] Count words in a user-input string in C

查看:152
本文介绍了计算C中用户输入字符串中的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我们在课堂上给了这个程序。 用C语言编写一个程序,以计算用户输入的句子中的单词数。
这是我能想到的,但是单词的数量总是比正确的数量少一个。我的老师告诉大家,在打印字数之前,只需在字数上加1。我认为这是一个错误,如果我们不输入任何单词,即按Enter键而不是输入,我的老师建议的程序仍会将单词数设为1而不是0。您知道以任何方式获取正确的单词算不算最后加1?
代码:

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:

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

My code(giving 1 less than correct) :

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


推荐答案

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

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.

这篇关于计算C中用户输入字符串中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆