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

描述

将一个英文语句以单词为单位逆序排放。例如“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;
} 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值