如何取字符串的反面

How to take reverse of string

本文关键字:字符串 何取      更新时间:2023-10-16

我有字符串

 string s1="5 2 13 * +" //as prefix expression.

我想得到上面矩阵的反转。

"+ * 13 2 5"

我尝试过字符串流,但它生成了"+ * 31 2 5",我丢失了"13",得到了"31"。这对我的计算不好。

我该怎么办?谢谢你的帮助。

假设要反转的是str,并且值之间的分隔符是空白字符:

stringstream ss(str);
string answer, current;
answer.clear();
while (ss >> current) answer = current + " " + answer;
answer.erase(answer.size()-1, 1);     // eliminate space in the end of answer

另一种方式

    std::string s = "5 2 13 * +";
    std::forward_list<std::string> lst;
    std::istringstream is( s );
    for ( std::string t; std::getline( is, t, ' ' ); ) lst.push_front( t );
    s.clear();
    for ( std::string t : lst ) s += t + ' ';
    std::cout << "s = " << s << std::endl;

或者没有std::getline

    std::string s = "5 2 13 * +";
    std::forward_list<std::string> lst;
    std::istringstream is( s );
    while ( is >> s ) lst.push_front( s );
    s.clear();
    for ( std::string t : lst ) s += t + ' ';
    std::cout << "s = " << s << std::endl;