gpt4 book ai didi

c++ - 解析嵌套的CSS结构

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:33:27 25 4
gpt4 key购买 nike

我想编写一个小的代码分析器来解析嵌套结构并将其转换为有效的 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;
}

那么,如何保留从上层继承下来的标识符呢?

最佳答案

如果您使用的是 C++,为什么不使用 OO?

创建一个表示范围(匹配的 {} 对)的类,它有一个指向其子范围的指针列表和一个指向其父范围的指针:即:从您的示例 foo 的列表中包含 a 和 b,b 的列表包含 c.

打印时,递归进入每个叶作用域,然后通过将所有“祖先”的名称添加到它自己的开头来让它打印其“完整”名称。

骨架起点:

class Element
{
public:
Element()
: m_pParent( 0 )
{
}


private:

std::string m_Name;
std::string m_Contents;

Element* m_pParent;
std::list<Element*> m_Children;

};

关于c++ - 解析嵌套的CSS结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9052058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com