如何计算在c中的字符串中找到的单词数
How to count number of words found in a string in c
我正在尝试编写一个程序来计算字符串中找到的单词数,但是我编写的程序计算的是空格数。我如何构建这个程序——尽可能高效——来计算单词的数量?我怎么说字符串包含 4 个单词和 8 个空格,或者如果它不包含单词而只包含空格?我 missing/doing 哪里错了?
#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);
}
试试这个条件来计算字数:
if(text[i]!=' ' && text[i+1]==' ')
Count=count+1;
检测并计算单词的开头,space 到非 space 的转换:
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;
}
}
我正在尝试编写一个程序来计算字符串中找到的单词数,但是我编写的程序计算的是空格数。我如何构建这个程序——尽可能高效——来计算单词的数量?我怎么说字符串包含 4 个单词和 8 个空格,或者如果它不包含单词而只包含空格?我 missing/doing 哪里错了?
#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);
}
试试这个条件来计算字数:
if(text[i]!=' ' && text[i+1]==' ')
Count=count+1;
检测并计算单词的开头,space 到非 space 的转换:
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;
}
}