#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char string[81];
int i, num=0,word =0;
char c;
gets(string);
for(i=0; (c=string[i])!='\0'; i++) //只要不是字符'\0'就繼續循環
{
if(c==' ')
word=0;
else if (word==0)
{
word=1;
num++;
}
}
printf("There are %d words in the line.\n", num);
return 0;
}
改新版思路: 單詞後面出現一個不是字母的字符,則這個單詞結束。擴展了字符串中的標點
/******************************************************
6.8 Count how many words
Plan:
If a charactor is not a letter, and before it there is a letter,
count add
CREATE----------------------------
By: Idooi Liu
Time: 2015/09/27-1022
----------------------------------
******************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool ifALetter(char charactor);
int main(void)
{
int i, number=0;
char stringMe[100];
gets(stringMe);
for(i=0; i<100; i++)
{
if(stringMe[i+1]=='\0') //出現字符'\0'結束循環
{
if(ifALetter(stringMe[i]))
number++;
break;
}
//單詞的最後一個字符判斷,下一個字符不是字母,單詞結束
if(ifALetter(stringMe[i]) && !ifALetter(stringMe[i+1]))
number++;
}
printf("There are %d words in the line.\n", number);
getchar();
return 0;
}
//判斷字符是否是字母
bool ifALetter(char x)
{
if((x>64 && x<91) || (x>96&&x<122))
return true;
else
return false;
}