1.题意:编写函数计算出一个字符串中单词的个数!该字符串中可能包含标点符号和空格,单独的标点符号不算入单词数
2.解题思路:首先,我们可以写一个函数判断输入的字符是不是字母。如果不是,说明这就是一个单词了,对其进行累加。继续判断后面的字符,如此一来。字符串中单词的数目就累加出来了。
3.参考代码:
#include<iostream>
using namespace std;
bool isletter(char a)
{
if(a>='a'&&a<='z'||a>='A'&&a<='Z')
return 1;
else
return 0;
}
int number(char word[])
{
int i,cnt=0,j;
for(i=0;word[i]!='\0';i++)
{
if(isletter(word[i])==1)
{
for(j=i+1;word[j]!='\0';j++)
{
if(isletter(word[j])==0)
{
break;
}
}
cnt++;i=j;
}
}
return cnt;
}
int main()
{
char sentence[500];
cin.getline(sentence,500);
int k;
k=number(sentence);
cout<<k<<endl;
return 0;
}
4.解决本题是应注意如何判断什么时候是一个单词,然后对其累加