用括号分割字符串中的参数
splitting parameters in a string with parenthesis
我想找到一种有效的方法来拆分这种字符串并将参数存储在变量中:
param1 (param2 param3) (param4 param5) ... param6
示例:
1. (10 10) (10 15) (2 11) 2.
1. (12 20) 2.
(有一个未定义数量的括号,每两个数字由 space 分隔)
我必须将第一个和最后一个参数存储在双精度型中,并将括号中的数字存储在向量中。
对于第二个例子,它将给出:
double beginOfLine, endOfLine
vector<int> vec1;
vector<int> vec2;
beginOfLine = 1.;
endOfLine = 2.;
vec1.push_back(12);
vec2.push_back(20);
我觉得 python 很容易。但在 C++ 中,我无法以简单的方式做到这一点。
nb:我不允许使用 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;
}
我想找到一种有效的方法来拆分这种字符串并将参数存储在变量中:
param1 (param2 param3) (param4 param5) ... param6
示例:
1. (10 10) (10 15) (2 11) 2.
1. (12 20) 2.
(有一个未定义数量的括号,每两个数字由 space 分隔)
我必须将第一个和最后一个参数存储在双精度型中,并将括号中的数字存储在向量中。
对于第二个例子,它将给出:
double beginOfLine, endOfLine
vector<int> vec1;
vector<int> vec2;
beginOfLine = 1.;
endOfLine = 2.;
vec1.push_back(12);
vec2.push_back(20);
我觉得 python 很容易。但在 C++ 中,我无法以简单的方式做到这一点。
nb:我不允许使用 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;
}