計算字符串中有多少個單詞。
要求:輸入一行字符,每個單詞之間用空格分開,最後的字符不能爲空。
#include <iostream>
#include<stdio.h>
using namespace std;
int main()
{
char cstring[100];
int ilndex,iword=1;
char cblank;
gets(cstring);
if(cstring[0]=='/0')/*判斷是否爲空*/
{
printf("there is no char\n");
}
else if(cstring[0]==' ')/*判斷是否爲空格*/
{
printf("first char just is a blank!\n");
}
else
{
for(ilndex=0;cstring[ilndex]!='\n';ilndex++)
{
cblank=cstring[ilndex];
if(cblank==' ')
{
iword++;
}
}
printf("%d\n",iword);
}
return 0;
}
結果