C++: 取消字符串首尾空字符,然后分割字符串,最后反向输出

本文介绍了一种使用C++实现的字符串逆序词组算法。通过Trim和Split两个辅助函数,首先去除输入字符串的首尾空白字符,然后按空格分割字符串为单词数组,最后逆序连接单词数组得到逆序词组的字符串。该算法适用于多种编程场景,特别是需要处理英文句子逆序词组的情况。

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

Description
Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

/*
很多其他语言的libary都会有去除string类的首尾空格的库函数,但是标准C++的库却不提供这个功能。
但是C++string也提供很强大的功能,实现trim这种功能也不难。
*/

#include <iostream>
#include <string>
#include <cstring>
#include <tchar.h>  // for "_T" declare
#include <vector>

using namespace std;
class Solution {
public:
    string reverseWords(string &s) {
        // write your code here
        string revWords = "";
        string TrimRes = Trim(s);
        vector<string> DelimStr = Split(TrimRes, " ");
        revWords = DelimStr[DelimStr.size()-1];
        for(int i=DelimStr.size()-2; i>=0; i--)
        {
            //revWords = DelimStr[i] + " " + revWords;
            revWords = revWords + " " + DelimStr[i];
        }
        return revWords;
    }

    string & Trim(string &str)
    {
        if(str.empty())
            return str;
        str.erase(0, str.find_first_not_of(" "));
        str.erase(str.find_last_not_of(" ") + 1);
        return str;
    }
    vector<string> Split(const string &str, const string &delim)
    {
        vector<string> res;
        if(str == "")
            return res;
        char *strs = new char[str.length() + 1];
        strcpy(strs, str.c_str());
        char *d = new char[delim.length() + 1];
        strcpy(d, delim.c_str());

        char *p = strtok(strs, d);
        while(p)
        {
            string s = p;
            res.push_back(s);
            //res = res + " " + s;
            p = strtok(NULL, d);
        }
        return res;
    }
};
int main()
{
    string s1 = " the sky is blue!  one parameter        ll?  ";
    Solution slu;
    string s2 = slu.reverseWords(s1);
    cout<<"The Reverse Words is:"<<endl;
    cout<<s2<<endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值