Parse indented text tree in Java

后端 未结 4 1349
旧时难觅i
旧时难觅i 2020-12-19 14:38

I have an indented file that I need to parsed using java, I need some way to place this in a Section class as shown below

    root
     root1
       text1
           


        
4条回答
  •  一生所求
    2020-12-19 15:00

    Surprisingly complex problem... but here's a pseudocode

    intialize a stack
    push first line to stack
    while (there are more lines to read) {
     S1 = top of stack // do not pop off yet
     S2 = read a line
     if depth of S1 < depth of S2 {
      add S2 as child of S1
      push S2 into stack
     }
     else {
      while (depth of S1 >= depth of S2 AND there are at least 2 elements in stack) {
       pop stack
       S1 = top of stack // do not pop
      }
      add S2 as child of S1
      push S2 into stack
     }
    }
    return bottom element of stack
    

    where depth is the # leading whitespaces. You might have to either modify or wrap the Section class to store the depth of the line.

提交回复
热议问题