[英]How to count number of words found in a string in c
我正在尝试编写一个程序来计算在字符串中找到的单词数,但是我编写的程序会计算空格数。 我如何构建这个程序 - 尽可能高效 - 来计算字数? 我该怎么说字符串包含 4 个单词和 8 个空格,或者如果它不包含单词而只包含空格? 我错过了什么/做错了什么?
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
int main(void)
{
string text = get_string("Text: ");
int count_words = 0;
for (int i = 0, n = strlen(text); i < n; i++)
{
if (isspace (text[i]))
{
count_words++;
}
}
printf("%i\n", count_words + 1);
}
检测和计算单词的开头,空格到非空格的转换:
int count_words = 0;
bool begin = true;
for (int i = 0, n = strlen(text); i < n; i++) {
if (isspace (text[i])) {
begin = true;
} else {
if (begin) count_words++;
begin = false;
}
}
试试这个条件来计算单词:
if(text[i]!=' ' && text[i+1]==' ')
Count=count+1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.