C程序计算给定string/sentence中的单词数?
C program to count words in a given string/sentence?
我想通过计算给定字符串之间的空格来计算给定字符串中的单词数。这是我试过的代码。
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
int t,i,b=1;
char a[100];
printf("Enter a sentence: ");
gets(a);
t=strlen(a);
for(i=0;a[i]!='[=11=]';i++)
{
if(a[i]=' ')
{
b++;
}
}
printf("The number of words in the above sentence are %d",b);
getch();
}
但是我无法得到输出。我总是弄错字数。
谢谢。 :D
您正在使用赋值运算符 =
进行比较
if(a[i]=' ')
你需要==
if(a[i] == ' ')
有人用这个
if (' ' == a[i])
防止这种错误。
我想通过计算给定字符串之间的空格来计算给定字符串中的单词数。这是我试过的代码。
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
int t,i,b=1;
char a[100];
printf("Enter a sentence: ");
gets(a);
t=strlen(a);
for(i=0;a[i]!='[=11=]';i++)
{
if(a[i]=' ')
{
b++;
}
}
printf("The number of words in the above sentence are %d",b);
getch();
}
但是我无法得到输出。我总是弄错字数。
谢谢。 :D
您正在使用赋值运算符 =
进行比较
if(a[i]=' ')
你需要==
if(a[i] == ' ')
有人用这个
if (' ' == a[i])
防止这种错误。