应用C++的string类对象实现。具体做法是:从键盘输入英文句子到string类对象s,然后遍历该对象(字符串),以字母开始以字母结束,中间只有字母和'-'的被认为是一个单词;在判断过程中把它们组装到另一个string类对象st中。此后再遇到不是字母或'-'时输出st(单词),输出后将st置空表示该单词已输出,并将单词计数器sum增1。举例代码如下:
//#include "stdafx.h"//If the vc++6.0, with this line.
#include
#include
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();iif(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;
}
执行结果示例如下图:
#include
#include "string.h"
void main()
{
char str[200];
char *string;
int i=0,k=0,j;
char str1[20][10];
cin.getline(str,200) ;
string=str;
for(;*string!='\0';string++)
{
if(*string==' ')
{
str1[k][i]='\0';
i=0;
k++;
}
str1[k][i]=*string;
i++;
}
if((str1[k][i]>'a'&&str1[k][i]<'z')||(str1[k][i]>'A'&&str1[k][i]<'Z'))
str1[k][i]='\0';
else
str1[k][i-1]='\0';
cout<<"一共有"<
cout<<"分别是:";
for(j=0;j
cout<
cout<
}
严格按照楼主的意思编的,句子如果有符号也能去除。
方法很多,下面是一种较简单的,你可以在此基础上修改:
#include
#include
using namespace std;
int main()
{
char s[100],temp[20];
gets(s);
int i=0,j=0;
while(s[i]){
while(s[i]!=' ')
{temp[j]=s[i];i++;j++;}
temp[j]='\0';
if(j>0)cout<
i++;j=0;
}
cout<
return 0;
}
C + + input number of judging an English sentence with the word And output each respectively
可以吗
对输入的字符串判断分隔符就行了