应用C++的string类对象实现。具体做法是:从键盘输入英文句子到string类对象s,然后遍历该对象(字符串),以字母开始以字母结束,中间只有字母和'-'的被认为是一个单词;在判断过程中把它们组装到另一个string类对象st中。此后再遇到不是字母或'-'时输出st(单词),输出后将st置空表示该单词已输出,并将单词计数器sum增1。举例代码如下:
//#include "stdafx.h"//If the vc++6.0, with this line.
#include <string>
#include <iostream>
using namespace std;
int main(void){
string st,s;
int i,j,k,ln,sum;
char ch;
cout << "Please enter an English sentence...\n";
while(s+=(ch=cin.get()),ch!='\n');//输入一个英文句子
cout << endl;
for(sum=i=0,ln=s.length();i<ln;i++){//判断单词
if(s[i]>='A' && s[i]<='Z' || s[i]>='a' && s[i]<='z' || s[i]=='-')
st+=s[i];//以字母始字母终,中间只有字母和'-'的就组织成单词存入st
else if(st!=""){
cout << st << endl;//输出该单词(一个一行)
sum++;//单词个数增1
st="";//st置空,表示该单词已输出
}
}
cout << "\nA total of " << sum << " word(s).\n";//最后输出单词个数
return 0;
}
执行结果示例如下图: