我尝试解析一个类似于"1,4-6,8-10,12“的字符串,并将结果转换为int/ push_back *的向量。在解析时,如果逻辑遇到4-6,那么它应该在向量中推入整数4、5和6。我尝试使用strtok来实现这一点,但是它修改了输入字符串的唯一副本,所以我什么也得不到。我不能使用boost,否则tokenizer将是非常简单和有用的。
发布于 2013-05-29 16:40:27
#include <stlport\sstream>
#include <stlport\vector>
using namespace std;
...
stringstream ss("1,4-6,8-10,12");
vector<int> v;
int x, x2;
char c;
while (ss >> x)
{
v.push_back(x);
if (!(ss >> c))
break; // end of input string
if (c == '-')
{
if (!(ss >> x2))
throw; // incorrect input string
for (int i = x+1; i <= x2; i++)
v.push_back(i);
if (!(ss >> c))
break; // end of input string
}
else if (c != ',')
throw; // incorrect input string
}
// check
int s = v.size();
// s = 8, v:{1,4,5,6,8,9,10,12}发布于 2013-05-29 14:46:07
std::stringstream ss("1,4-6,8-10,12");
std::vector<int> v;
int x;
while(ss >> x)
{
v.push_back(x);
char c;
ss >> c; //will just discard a non space char.
if(c != ',' || c != '-') ss.unget(); //... unless is just , or -
}写这篇文章的时间:1分钟。搜索合适的算法函数的时间:至少5分钟。
自己决定什么更有效率。
https://stackoverflow.com/questions/16807114
复制相似问题