在带括号的字符串中拆分参数

splitting parameters in a string with parenthesis

本文关键字:拆分 参数 字符串      更新时间:2023-10-16

我想找到一种有效的方法来拆分这种字符串并将参数存储在变量中:

param1 (param2 param3) (param4 param5) ... param6

例:

1.  (10 10) (10 15) (2 11) 2.
1.  (12 20) 2.

(有一个未定义的括号,每 2 个数字用空格分隔)

我必须将第一个和最后一个参数存储在双精度中,并将数字存储在向量中的括号中。

对于第二个示例,它将给出:

double beginOfLine, endOfLine
vector<int> vec1;
vector<int> vec2;
beginOfLine = 1.;
endOfLine = 2.;
vec1.push_back(12);
vec2.push_back(20);

我发现在python中很容易。但C++我无法以简单的方式做到这一点。

注意:我不允许使用 boost/C++11 及更高版本

由于您不能使用 C++11,因此使用std::stringstream进行一些基本的字符串拆分可能会完成这项工作。我不确定<limits>何时是 C++11 的一部分,但您可以轻松地用另一个最大值替换它们。

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <limits>
int main()
{
double beginOfLine = 0.0, endOfLine = 0.0;
std::vector<int> vec1;
std::vector<int> vec2;
std::stringstream ss("1.  (10 10) (10 15) (2 11) 2.");
ss >> beginOfLine;
while (true) {
int first, second;
ss.ignore(std::numeric_limits<std::streamsize>::max(), '(');
ss >> first >> second;
vec1.push_back(first);
vec2.push_back(second);
ss.ignore(std::numeric_limits<std::streamsize>::max(), ')');
ss.ignore(std::numeric_limits<std::streamsize>::max(), ' ');
if (ss.peek() != '(') {
ss >> endOfLine;
break;
}
}
std::cout << beginOfLine << 'n';
for (std::vector<int>::iterator it = vec1.begin(); it != vec1.end(); ++it)
std::cout << *it << ' ';
std::cout << 'n';
for (std::vector<int>::iterator it = vec2.begin(); it != vec2.end(); ++it)
std::cout << *it << ' ';
std::cout << 'n' << endOfLine;
return 0;
}