【问题标题】:Indenting Java Output缩进 Java 输出
【发布时间】:2010-06-29 11:03:32
【问题描述】:

我正在一个 Java 程序中生成一个 graphviz DOT 文件(这是一个看起来像的示例:http://www.graphviz.org/Gallery/directed/cluster.html)。我想根据大括号自动缩进这个文件。有没有一种简单的方法可以在 Java 中做到这一点?谢谢!

【问题讨论】:

    标签: java indentation graphviz


    【解决方案1】:

    像这样的嵌套上下文确实最好通过堆栈来表示,但是您可以通过计数来进行这种解析的廉价版本——它不是真正“正确”的,因为它不是一个完整的解析器(一方面,这不'不考虑 cmets,它可能还有其他几种可能会破坏的方式,例如包含括号的名称),但对于一次性使用来说已经足够了:

    伪代码

    int indent=0;
    for (line):
        print ('\t' for each indent) + line
        if (line.contains('{'))indent++
        if (line.contains('}')} indent --;
    

    如果您的示例输出显示的括号中的行尚未中断,请通过在换行符、“{”或“}”上中断输入来迭代行。

    【讨论】:

      【解决方案2】:

      我想这个问题有多种解决方案。根据要求,您可能需要一个优雅的解决方案,它可以让您轻松地为最终输出创建模板。然后,您需要了解 graphviz 文件格式,并可能按块将代码识别为节点。然后工作很简单:深度为 i 的输出节点(我的意思是代表节点的代码),缩进 = i*4 个空格。

      由于我对 graphviz 文件一无所知,我可能会简单地将其视为纯文本文件。 所以你需要做的就是

        1. open the graph file, 
        2. create a temp file for the final output
        3. set indent = 0.
        4. read one line, if not null, search the line for braces, for every opening brace, ++indent
           and --indent for every closing brace.
        NOTE:you need to escape the escaped braces if there is any. say "{" or \{
      
      
        5. write the line to the temp file with preceding spaces = 4*indent (assuming you want 4 spaces for every indent)
        6. close both files. if needed, replace the old file with the temp file.
      

      由于我可能无法正确理解您的问题,因此伪代码在功能上可能毫无用处。但你明白了;-)

      【讨论】:

        猜你喜欢
        • 2011-02-04
        • 1970-01-01
        • 1970-01-01
        • 2012-07-29
        • 1970-01-01
        • 2010-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多