2011-12-25 94 views
0

我有一個字符串,我想解析一個結構塊。如何解析結構化格式?

因此,結構字符串是這樣的:

if(true) { 
    if(true) { 
     if(true) {} 
    } 
} 
if(true) { 
    if(true) { 
     if(true) {} 
    } 
} 

而且我想分裂這樣的父塊一個:

if(true) { 
    if(true) { 
     if(true) {} 
    } 
}, 

if(true) { 
    if(true) { 
     if(true) {} 
    } 
} 

我的代碼:

string condition = 
"if(true) {\ 
    if(true) {\ 
     if(true) {}\ 
    }\ 
}\ 
if(true) {\ 
    if(true) {\ 
     if(true) {}\ 
    }\ 
}"; 

string item; 
stringstream stream(condition); 
vector<string> array; 

//splitting on sections 
while (getline(stream, item, '}')) { 
    array.push_back(item + "}"); 
} 

for(int i = 0; i < array.size(); i++) { 
    cout << i << array[i] << endl; 
} 

結果:

0 if(true) { if(true) { if(true) {} 
1 } 
2 } 
3 if(true) { if(true) { if(true) {} 
4 } 
5 } 

但需要:

0 if(true) { if(true) { if(true) {} } } 
1 if(true) { if(true) { if(true) {} } } 

如何檢測和更正確解析父塊,講述一個算法?

+0

好像要分割字符串?如果這是真的看看這裏的一些解決方案:http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c – 2011-12-25 19:35:44

+0

謝謝,我已經看到了這篇文章,但我有一個問題稍有不同。我不明白算法解析。 – 2011-12-25 19:49:42

+0

@AlexanderGuiness:您可能需要查看Boost.Spirit的一些高級功能解析。 – GManNickG 2011-12-25 19:50:32

回答

2

您需要對當前深度進行計數。我發現最好的解析器是基於迭代器的,所以這就是我在這裏展示的。除非使用最簡單的格式,否則std::getline對解析不是很有用。

完全未經測試的代碼:

std::vector<std::string> vec; 

int depth = 0; 
std::string::const_iterator first = condition.begin(), 
          last = condition.end(), 
          iter = first; 

for(;;) 
{ 
    iter = std::find_if(iter, last, 
         [](char ch) { return ch == '{' || ch == '}'; }); 

    if(iter == last) 
    { 
     if(depth) 
     { 
      throw std::runtime_error("unclosed block found."); 
     } 

     break; 
    } 

    if(*iter == '{') 
    { 
     ++depth; 
     ++iter; 
    } 
    else if(*iter == '}' && !--depth) 
    { 
     v.push_back(std::string(first, ++iter)); 
     first = iter; 
    } 
    else 
    { 
     ++iter; 
    } 
}