0
点赞
收藏
分享

微信扫一扫

华为机试题——HJ13 句子逆序

陬者 2022-04-19 阅读 49
c++

描述

将一个英文语句以单词为单位逆序排放。例如“I am a boy”,逆序排放后为“boy a am I”

所有单词之间用一个空格隔开,语句中除了英文字母外,不再包含其他字符

数据范围:输入的字符串长度满足 1 \le n \le 1000 \1≤n≤1000

注意本题有多组输入

输入描述:

输入一个英文语句,每个单词用空格隔开。保证输入只包含空格和字母。

输出描述:

得到逆序的句子

示例1

输入:

I am a boy

复制输出:

boy a am I

复制

示例2

输入:

nowcoder

复制输出:

nowcoder

注意:代码中“while(index != -1)”判断字符串结束这样就可以,但是如果改为“while(str[i] != '\0') ”结果会导致少一部分字符串,不明所以。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <string.h>
#include <malloc.h>
#include <sstream>
#include <algorithm>
#include <cstring>
#include <map>
#include <set>
#include <vector>


void print(std::vector<std::string> strVect)
{
    for(int i = 0; i < strVect.size(); ++i)
    {
        std::cout << strVect.at(i) << " ";
    }
    std::cout << std::endl;
}
//I am a boy
void SentenceReverse(std::string str)
{
    std::string copyStr(str);
    std::vector<std::string> strVect;
    int len = strlen(str.c_str());
    int i = 0;
    int index = 0;
    while(index != -1)
    {
        index = str.find(' ');
        std::string temp = str.substr(0, index);
        strVect.push_back(temp);

        str = str.substr(index + 1, len - strlen(temp.c_str() - 1));
        i++;
    }
    // int lastIndex = copyStr.find_last_of(' ');
    // strVect.push_back(copyStr.substr(lastIndex + 1, len - lastIndex));

    std::reverse(strVect.begin(), strVect.end());
    print(strVect);

}

int main()
{
    std::string str;
    getline(std::cin, str);
    // std::cout << "------------------\n";
    SentenceReverse(str);

    return 0;
} 
举报

相关推荐

0 条评论