2
我想寫一個小的代碼分析器來分析嵌套結構並將其翻譯爲有效的CSS
。但是,我沒有保留從上層繼承的標識符。解析嵌套的CSS結構
嵌套結構:
#foo {
border: 1px;
a {
border: 2px;
}
b {
border: 3px;
c {
border: 4px; /* comment */
}
}
}
我想結構翻譯成:
#foo {
border: 1px;
}
#foo a {
border: 2px;
}
#foo b {
border: 3px;
}
#foo b c {
border: 4px; /* comment */
}
解析代碼:
#include <iostream>
#include <iterator>
#include <string>
using namespace std;
int main() {
string str = "\
#foo {\
border: 1px;\
a {\
border: 2px;\
}\
b {\
border: 3px;\
c {\
border: 4px; /* comment */\
}\
}\
}";
string::const_iterator i = str.end(),
begin = str.begin(), end;
while (i != begin) {
if (*i == ';' || (*i == '/' && *(i-1) == '*')) {
end = i++;
while (*i-- != '{');
while (true) {
if (*i == ';' || *i == '}' || *i == '{' || i == begin)
break;
i--;
}
string item(++i, ++end);
cout << item << "}" << endl;
}
i--;
}
return 0;
}
日期:
c {
border: 4px; /* comment */
}
b {
border: 3px;
}
a {
border: 2px;
}
#foo {
border: 1px;
}
那麼,如何保留從上層繼承的標識符呢?
如果你不這樣做純粹是作爲一個練習的時候,意識到已經有東西在那裏像[LESS CSS(http://lesscss.org/)這是做什麼的。 – icktoofay 2012-01-29 09:02:40
@icktoofay,我知道'LESS'非常好,我想用C++來做這件事。嵌套規則是唯一需要做的事 – 2012-01-29 09:07:24
您可以將標識符保留在堆棧中。當你沿着層次結構向上/向下時,你推/拉彈出。 – Alexander 2012-01-31 11:58:51