【发布时间】:2011-12-25 19:27:33
【问题描述】:
我有一个字符串,我想在结构块上解析它。
所以,字符串结构如下:
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) {} } }
如何更正确地检测和解析父块或告诉算法?
【问题讨论】:
-
好像要拆分字符串?如果这是真的,看看这里的一些解决方案:stackoverflow.com/questions/236129/how-to-split-a-string-in-c
-
谢谢,我已经看过那篇文章,但我有一个稍微不同的问题。我不懂要解析的算法。
-
@AlexanderGuiness:您可能想研究 Boost.Spirit 以进行一些高功能解析。
-
@GMan,我不想为此安装额外的库,而是想做一个简单的算法。