Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a stack to parse a string

I have a String:

String stringContent="{\\*\\listtable{\\list{\\listlevel{\\leveltext}{\\levelNumber}}}}"

How do I select values of all enclosing braces one by one in each pass like this:

"{\\levelNumber}"
"{\\leveltext}"
"{\\listlevel{\\leveltext}{\\levelNumber}}"
"{\\list{\\listlevel{\\leveltext}}}"
"{\\*\\listtable{\\list{\\listlevel{\\leveltext}}}}"

So far I've done this:

   public class StringExtracter {

public String stringofObject(Section parentSectionObject, String stringContent) {
    Stack stack=new Stack();
    String returnString = "";

    char arr[] = stringContent.toCharArray();


    for(int i=0;i<=arr.length;i++){

      while(arr[i]!='}'){
       if(arr[i]=='{'){
           stringContent=stringContent.substring(i+1);
           returnString=stringContent;
           System.out.println(stringContent);
           braces=true;
           Section sectionObject=new Section(parentSectionObject,stringContent);
          stack.push(arr[i]);


       }           

    }
    return returnString;
}

But the problem is that it is not detecting the right } like this. How should I be doing this?

Output as of now:

\*\listtable{\list{\listlevel{\leveltext}{\fefw}}}}
\list{\listlevel{\leveltext}{\fefw}}}}
\listlevel{\leveltext}{\fefw}}}}
\leveltext}{\fefw}}}}
\fefw}}}}
like image 240
Identity1 Avatar asked Aug 08 '15 10:08

Identity1


People also ask

How do I parse a specific string in Java?

Strings in Java can be parsed using the split method of the String class. ( StringTokenizer can also be used to parse a string; we won't be covering it here). This just gives a brief overview (and some examples) of some of the common (and easiest) ways to use the split method; for more detailed information see the Java API documentation for split .

What is the use of toString () method in Java stack?

The toString () method of Java Stack is used to return a string representation of the elements of the Collection.

How to stack characters from one string to another?

1) Create an empty stack. 2) One by one push all characters of string to stack. 3) One by one pop all characters from stack and put them back to string. Recommended: Please solve it on “ PRACTICE ” first, before moving on to the solution.

How do I parse a string with multiple pieces of information?

When we have a situation where strings contain multiple pieces of information (for example, when reading in data from a file on a line-by-line basis), then we will need to parse (i.e., divide up) the string to extract the individual pieces. Strings in Java can be parsed using the split method of the String class.


1 Answers

Stack-based solution (problably could be simpler, but let's solve the problem first):

public class Main {

    public static class Node {
        public int level;
        public String content = "";
        public List<Node> children = new ArrayList<>();
    }

    public static void main(String[] args) {

        String input="{\\\\*\\\\listtable{\\\\list{\\\\listlevel{\\\\leveltext}{\\\\levelNumber}}}}";

        Node root = null;
        Stack<Node> stack = new Stack<>();

        for(char c: input.toCharArray()) {
            if (c == '{') {
                Node n = new Node();
                n.level = stack.size() + 1;
                n.content += c;
                stack.push(n);
                if (root == null) root = n;
            } else if (c == '}') {
                Node n = stack.pop();
                n.content += c;
                if (!stack.isEmpty()) {
                    stack.peek().children.add(n);
                }
            } else {
                stack.peek().content += c;
            }
        }

        TreeTraverser<Node> treeTraverser = new TreeTraverser<Node>() {
            @Override
            public Iterable<Node> children(Node root) {
                return root.children;
            }
        };

        for(Node node : treeTraverser.preOrderTraversal(root)) {
            String indent = String.format("%" + node.level + "s", " ");
            System.out.println(indent + node.content);
        }
    }
}

Note: Google's Guava library is needed for the TreeTraverser

Output:

 {\\*\\listtable}
  {\\list}
   {\\listlevel}
    {\\leveltext}
    {\\levelNumber}

Edit 1: modified to create a tree after additional input from the OP

Edit 2: modified to treat the siblings correctly

like image 121
mzc Avatar answered Sep 22 '22 21:09

mzc