2013-05-29 48 views
0

我想解析一个看起来像“1,4-6,8-10,12”的字符串,并将结果push_back为ints/char *的向量。在解析时,如果逻辑遇到4-6,那么它应该将矢量4,5和6推入。我试图用strtok来做到这一点,但它修改了输入字符串的唯一副本,所以我没有得到任何地方。我无法使用boost或else tokenizer会非常容易和有用。C++使用多个分隔符使用内置的c/C++解析字符串

+0

复印串入一个'矢量'(包括空字符),然后使用'strtok'。 – Praetorian

+0

你也可以使用'string :: find'和'string :: substr':find',',提取子字符串,检查substring是否包含' - ',如果是使用'string :: find'提取这两个数字, string :: substr'并处理该情况,否则插入该数字。 –

+0

为此使用'sscanf()'。忘记'strtok()'。 –

回答

0
#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} 
+1

我在strtok上浪费了太多时间。谢谢。 – alphabit

0
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分钟。

决定自己什么更有成效。

相关问题