C++ 如何取字符串的倒数
我有绳子C++ 如何取字符串的倒数,c++,c,string,C++,C,String,我有绳子 string s1="5 2 13 * +" //as prefix expression. 我想得到上面矩阵的倒数,像这样 “+*13 2 5” 我尝试了stringstream,但它使“+*31 2 5”,我丢失了“13”,我得到了“31”。这不利于我的计算 我该怎么办?感谢您的帮助。假设您要反转的是str,并且值之间的分隔符是空白字符: stringstream ss(str); string answer, current; answer.clear(); while (s
string s1="5 2 13 * +" //as prefix expression.
我想得到上面矩阵的倒数,像这样
“+*13 2 5”
我尝试了stringstream,但它使“+*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
假设要反转的是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::string s=“5 2 13*+”;
std::转发列表lst;
std::istringstream为(s);
对于(std::string t;std::getline(is,t',);)lst.push_front(t);
s、 清除();
对于(std::string t:lst)s+=t+'';
std::cout另一种方法
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::string s=“5 2 13*+”;
std::转发列表lst;
std::istringstream为(s);
对于(std::string t;std::getline(is,t',);)lst.push_front(t);
s、 清除();
对于(std::string t:lst)s+=t+'';
std::cout@juanchopanza“13”仍然会被颠倒,对吗?@bitfidlingcodemonkey愚蠢的我,我一直认为问题的标题意味着什么。看起来你不想颠倒“字符串”。您有一个像[[“5”]、[“2”]、[“13”]、[“*”]、[“+”]”这样的二维数组,并且希望反转外部数组。希望这也能回答您的问题:-)您可能需要strok()
注意,这可能不是您真正想问的问题的答案,即如何将后缀改为前缀。正确答案是+5*2 13
。当然,+
和*
是可交换的,因此最终结果是相同的,但有些运算符不是。例如,试试看,5 2 13/-
这肯定与前缀表达式-/13 2 5
@juanchopanza“13”会被颠倒,对吗?@bitfidlingcodemonkey,我一直认为问题标题有意义。看起来你不想颠倒“字符串”。您有一个像[[“5”]、[“2”]、[“13”]、[“*”]、[“+”]”这样的二维数组,并且希望反转外部数组。希望这也能回答您的问题:-)您可能需要strok()
注意,这可能不是您真正想问的问题的答案,即如何将后缀改为前缀。正确答案是+5*2 13
。当然,+
和*
是可交换的,因此最终结果是相同的,但有些运算符不是。例如,尝试使用5 2 13/-
,它肯定与前缀表达式-/13 2 5
不同。它返回相同的字符串。没有倒转@对不起,我弄错了。我用新代码编辑了我的答案,您可以试试。谢谢您上次编辑的答案正确且非常简单。:)它返回相同的字符串。没有倒转@对不起,我弄错了。我用新代码编辑了我的答案,您可以试试。谢谢您上次编辑的答案正确且非常简单。:)