Recursive way to parse a string

John Doe :

I have a string "{x{y}{a{b{c}{d}}}}" And want to print out recursively.

x
-y
-a
--b
---c
---d

This is what I have so far -

private static void printPathInChild2(String path) {

        if (path.length() == 0) {
            return;
        }
        if (path.charAt(0) == '{') {
            for (int i = 0; i < path.length(); i++) {
                if (path.charAt(i) == '{' && i != 0) {
                    String t1 = path.substring(0,i);
                    System.out.println(t1);
                    printPathInChild2(path.substring(i));
                } else if (path.charAt(i) == '}') {
                    String t2 = path.substring(0, i+1);
                    System.out.println(t2);
                    printPathInChild2(path.substring(i+1));
                }
            }
        }
    }

Struggling with the termination logic

Eran :

If you want to add '-' characters that depend on the depth of the nesting, you should pass a second argument to the recursive call, which keeps track of the prefix of '-' characters.

When you encounter a '{', you add a '-' to the prefix.

When you encounter a '}', you remove a '-' from the prefix.

When you encounter any other character, you print the prefix followed by that character.

private static void printPathInChild2(String path,String prefix) {
    if (path.length() == 0) {
        return;
    }
    if (path.charAt(0) == '{') {
      printPathInChild2(path.substring(1),prefix + "-");
    } else if (path.charAt(0) == '}') {
      printPathInChild2(path.substring(1),prefix.substring(0,prefix.length()-1));
    } else {
      System.out.println (prefix.substring(1) + path.charAt(0));
      printPathInChild2(path.substring(1),prefix);
    }
}

When you call this method with:

printPathInChild2("{x{y}{a{b{c}{d}}}}","");

You get:

x
-y
-a
--b
---c
---d

(I see that in your expected output 'd' has 4 '-'s, but I think it's an error, since 'd' has the same nesting level as 'c', so it should have 3 '-'s).

The method can also be written as follows:

private static void printPathInChild2(String path,String prefix) {
    if (path.length() == 0) {
        return;
    }
    char c = path.charAt(0);
    if (c == '{') {
      prefix = prefix + '-';
    } else if (c == '}') {
      prefix = prefix.substring(0,prefix.length()-1);
    } else {
      System.out.println (prefix.substring(1) + c);
    }
    printPathInChild2(path.substring(1),prefix);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=358183&siteId=1