1009 说反话 (20分)

题目地址:https://pintia.cn/problem-sets/994805260223102976/problems/994805314941992960

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

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

输入格式:

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

输出格式:

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

输入样例

Hello World Here I Come

输出样例

Come I Here World Hello

我的理解

从后往前,每遇到一个空格,输出这个空格之后的一个单词,然后更改单词尾的位置。在遍历一遍之后,因为第一个单词之前没有空格,所以剩余第一个单词未输出,输出第一个单词即可。

代码段

#include<iostream>
//#include<string>
#include<string.h>
using namespace std;
int main() {
    //  #include<string> 中的函数 
    //  string words;
    //  getline(cin, words);

    char words[80];
    // #include<string.h> 中的函数  
    // 第二位参数代表允许输入的字符个数,小于,不会等于 ,例如81 只能输入80个字符 
    cin.getline(words, 81);
    int length = strlen(words);
    int indexA = length - 1;
    int indexZ = length;
    for ( ; indexA >= 0; indexA--) {
        if (words[indexA] == ' ') {
            for (int index = indexA + 1; index < indexZ; index++) {
                cout << words[index];
            }
            cout << ' ';
            indexZ = indexA;
        }
    }
    // 循环结束后,indexA 等于 -1;
    // 剩余第一个单词未输出
    for (indexA++; indexA < indexZ; indexA++) {
        cout << words[indexA];
    }
    return 0;
}
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄