c++ 输入一句英文句子 判断其中单词个数 并分别输出每个单词。

例如输入的是This is a book.
输出
有4个单词。
它们分别是: this,is,a,book。

应用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;
}

 执行结果示例如下图:

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-10-03
#include <iostream.h>

#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<<"一共有"<<k+1<<"个单词"<<endl;

 cout<<"分别是:";

 for(j=0;j<k;j++)

  cout<<str1[j]<<',';

 cout<<str1[j]<<endl;

}

严格按照楼主的意思编的,句子如果有符号也能去除。

本回答被提问者采纳
第2个回答  2015-04-07

方法很多,下面是一种较简单的,你可以在此基础上修改:

#include <iostream>

#include <string>

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<<temp<<',';

   i++;j=0;

  }

  cout<<endl;

 return 0;

}

本回答被网友采纳
第3个回答  2016-03-20
C + + input number of judging an English sentence with the word And output each respectively
可以吗
第4个回答  2015-04-07
对输入的字符串判断分隔符就行了追问

判断个数没问题,主要是分别输出

相似回答