我想将数学表达式分割为向量,因此我可以应用后缀表示法来解决方程式。我在互联网上找到了这个,但输出有点搞笑。我不能使用split
方法,因为它从结果中删除了分隔符。
3+cos(2)+2+1
我的预期输出是:
3
+
cos
(
2
)
+
2
+
1
但是我得到了类似的东西:
3+
cos(
2)
+
2+
1
我该如何解决这个问题?
这是我的代码:
vector<string> split(string& stringToSplit)
{
vector<string> result;
size_t pos = 0, lastPos = 0;
while ((pos = stringToSplit.find_first_of("+-*/()", lastPos)) != string::npos)
{
string value = stringToSplit.substr(lastPos, pos-lastPos+1);
result.push_back(value);
lastPos = pos+1;
}
result.push_back(stringToSplit.substr(lastPos));
return result;
}
int main()
{
string z = "3+cos(2)+2+1";
vector<string> d = split(z);
for(int i=0;i<d.size();i++)
{
cout<<d[i]<<endl;
}
getch();
return 0;
}
答案 0 :(得分:1)
这可能对您有用:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
std::vector<std::string> split(std::string &stringToSplit)
{
std::vector<string> result;
size_t pos = 0, lastPos = 0;
while((pos = stringToSplit.find_first_of("+-*/()", lastPos)) != string::npos)
{
string value = stringToSplit.substr(lastPos, pos - lastPos);
if(std::any_of(value.begin(), value.end(), [](char c) { return c != ' '; }))
result.push_back(value); // or you should trim the whitespaces instead and check whether value is not empty
result.push_back(stringToSplit.substr(pos, 1));
lastPos = pos + 1;
}
result.push_back(stringToSplit.substr(lastPos)); // the same trimming and check should be performed here
return result;
}
int main()
{
std::string z = "3+cos(2)+2+1";
std::vector<string> d = split(z);
for(unsigned int i = 0; i < d.size(); i++)
std::cout << d[i] << std::endl;
std::cin.get();
return 0;
}
代码将cos
之类的序列分别推送到向量(如果它不仅是空格),然后推送分隔符。