gpt4 book ai didi

C:计算字数(需要帮助修复)

转载 作者:太空宇宙 更新时间:2023-11-04 07:28:28 24 4
gpt4 key购买 nike

我是 C 编程的新手,正在尝试编写代码来计算字符串中的单词数。这是我计算代码数的代码。

    #include<stdio.h> 
#include<string.h>
void main()
{
int count=0,i,len;
char str[100];
printf("enter the sentence");
gets(str);
len=strlen(str);
for(i=0;i<=len;i++)
{
if(str[i]==' ')
count++;
}
printf("the number of words are :\t%d",count+1);
}

当我的输入是:这是四个词时,它工作正常。它给出输出字数是:4

我的问题是如何处理单词之间的“两个连续的空格”,输入的“开头的空格”“后面的空格”输入的最后”

最佳答案

不计算空格,而是计算每个单词的第一个非空格字符。

#include<stdio.h> 

int main()
{
int count=0;
char str[100];
printf("enter the sentence");
gets(str);

char *cur= str;

for (;;)
{
while (*cur == ' ')
{
cur++;
}

if (*cur == 0)
{
break;
}

count++;

while (*cur != 0 && *cur != ' ')
{
cur++;
}
}

printf("the number of words are :\t%d",count);

return 0;
}

关于C:计算字数(需要帮助修复),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16115974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com