151 Reverse Words in a String

本文介绍了一种使用C++实现的方法来反转字符串中的单词顺序。通过逐个处理空格分隔的单词,并将它们按相反顺序重新组合到一个新的字符串中,实现了题目要求的功能。示例代码展示了如何操作字符串并反转其内部单词的顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Reverse Words in a String
Given an input string, reverse the string word by word.
For example,
Given s = “the sky is blue”,
return “blue is sky the”.

class Solution {
public:
    void reverseWords(string &s) {
        int index = 0;
        string temp_str = "";

        while(EOF != (index = s.find_first_of(' ')))
        {
            temp_str.insert(0, s.substr(0,index));
            temp_str.insert(0, " ");
            s = s.erase(0, index+1);
        }
        temp_str.insert(0, s);
        s = temp_str;
    }
};

int main()
{
    string test = "the sky is blue";

    Solution().reverseWords(test);

    printf("result test: %s\n", test.c_str());
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值