2011-12-25 8 views
0

私は文字列を持っており、構造体ブロック上の文字列を解析したいと思います。構造化された形式を解析する方法は?

ので、このような文字列で構造:

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

そして、私はこのような親ブロックに1を分割したいと思います:

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 –

+0

ありがとう、私はすでにその投稿を見ましたが、私はわずかに異なる問題。私は解析するアルゴリズムを理解していません。 –

+0

@AlexanderGuiness:高機能の解析のために、Boost.Spiritを調べるとよいでしょう。 – GManNickG

答えて

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; 
    } 
} 
関連する問題