首页 > 解决方案 > 计算具有多个空格的字符串中的单词

问题描述

我需要可以计算字符串中的单词而不计算它们之间的多个空格的代码。

我可以编写一个程序来计算单词之间只有 1 个空格,但我不知道当它超过 1 个空格时我应该如何编码。我想像一个for循环来检查它之前的字符是否是一个空格,但我不知道该怎么做。我想提一下,我是 C 语言的初学者。

#include <stdio.h>
#include <string.h>

int main()
{
char s[200];
int count = 0, i;

printf("enter the string: ");
fgets(s,200,stdin);
for (i = 0;s[i] != '\0';i++)
{
    if (s[i] == ' ')
        count++;    
}
printf("number of words in given string are: %d\n", count+ 1);

return(0);
} 

标签: c

解决方案


您可以引入一个标志来判断前一个字符是否为空格。就像是:

#include <stdio.h>
#include <string.h>

int main()
{
    char s[200];
    int count = 0, i;
    int last_was_space = 1;

    printf("enter the string: ");
    fgets(s,200,stdin);
    for (i = 0;s[i] != '\0';i++)
    {
        if (s[i] == ' ')
        {
            if (!last_was_space) 
            {
                count++; // Only count when last char wasn't a space
                last_was_space = 1;
            }
        }
        else
        {
            // Update flag (unless this char is a newline)
            if (s[i] != '\n') last_was_space = 0;
        }
    }
    if (!last_was_space) ++count; // Count the last word if there wasn't a space before

    printf("number of words in given string are: %d\n", count);

    return(0);
}

推荐阅读