PAT 乙级 -- 1009 -- 说反话

题目简述

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

      输入格式:测试输入包含一个测试用例,在一行内给出总长度不超过80的字符串。字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,单词之间用1个空格分开,输入保证句子末尾没有多余的空格。

输出格式:每个测试用例的输出占一行,输出倒序后的句子。

输入样例
Hello World Here I Come

输出样例
Come I Here World Hello

思路

本题可自己实现split函数,C++使用STL类库较为方便。

C++代码样例

#include <iostream>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;

void split(vector<string>& str, const string& temp_str, const string& flag)
{
    string::size_type pos_start, pos_end;
    pos_start = 0;
    pos_end = temp_str.find(flag);
    while(string::npos != pos_end)
    {
        str.push_back(temp_str.substr(pos_start,pos_end-pos_start));
        pos_start = pos_end + flag.size();
        pos_end = temp_str.find(flag, pos_start);
    }
    if(pos_start != temp_str.length())
    {
        str.push_back(temp_str.substr(pos_start));
    }
    return;
}

int main(void)
{
    vector<string> str;
    string temp_str = "";
    int len = 0;
    char input_str[85] = "";
    gets(input_str);
    temp_str = input_str;
    split(str,temp_str," ");
    for(int i=str.size()-1; i>=0; i--){
        printf("%s",(char*)str[i].data());
        if(i != 0)
        {
            printf(" ");
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/csnd/p/12897035.html