C++ 反转字符串中的单词

180it 2020-10-13 PM 1157℃ 0条

include<iostream>

include<string>

include<sstream>

using namespace std;

class StrTools {
public:

string reverseWords(string s) {
    stringstream all(s);
    string word = "", res = "";
    while (all >> word) {
        res = word + " " + res;
    }
    return res.substr(0, res.size() - 1);
}
string reverseWords2(string s) {
    std::reverse(begin(s), end(s));
    stringstream all(s);
    string word = "", res = "";
    while (all >> word) {
        std::reverse(begin(word), end(word));
        res = res + " " + word;
    }
    return res.empty() ? "" : res.substr(1);
}

};

int main() {

string str="Hello, World!";
StrTools st;

std::cout << st.reverseWords(str.c_str()) << std::endl;
std::cout << st.reverseWords2(str.c_str()) << std::endl;
return 0;

}

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

C++ 反转字符串中的单词