5-32 说反话-加强版

来源:互联网 发布:电脑编程有几种 编辑:程序博客网 时间:2024/04/28 22:46

给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。

输入格式:

测试输入包含一个测试用例,在一行内给出总长度不超过500 000的字符串。字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,单词之间用若干个空格分开。

输出格式:

每个测试用例的输出占一行,输出倒序后的句子,并且保证单词间只有1个空格。

输入样例:

Hello World Here I Come
输出样例:

Come I Here World Hello

解答程序:

#include<cstdio>#include<cstdlib>#include<iostream>#include<cstring>#include<cmath>using namespace std;int main(){    char str[500001];    char *p;    gets(str);    int i=0,j=strlen(str)-1,count=0;    while(str[i]==' ')        i++;    /*当输入为空格时,结束程序*/    if(str[i]=='\0')        return 0;    //从后向前检测单词    while(j>=0)    {        if(str[j]==' ')        {            if(str[j+1]!=' '&&str[j+1]!='\0')            {                p=str+j+1;                count++;                if(count>1)                    cout<<" ";                cout<<p;            }            str[j]='\0';        }        else if(j==0&&str[j]!=' ')        {            p=str;            if(count>=1)                cout<<" ";            cout<<p;        }        j--;    }    cout<<endl;    system("pause");    return 0;}
0 0
原创粉丝点击