0

I have a string like this:

(A,X(B,C,D),X(E,F),G,H)

and i want to transform it to to an array like this :

[{A}, {X(B,C,D)}, {X(E,F)}, {G}, {H}]

The input String can have nested elements like this

(A,X(B,X(A,B),D))

I thought to do it with tree structure. What is the best way to do it in java ?

5
  • And? What is your question? Commented Jun 8, 2021 at 13:26
  • yes, then do it? Commented Jun 8, 2021 at 13:26
  • Use String.split(",") Commented Jun 8, 2021 at 13:38
  • @Sascha the String.split() does not work in this case Commented Jun 8, 2021 at 13:41
  • @Youssef Then you have to do it like a parser. Iterate over the chars and decide, if it is a comma you separate on or not. Have a flag for the info if its after an opening or closing bracket should help. Commented Jun 8, 2021 at 13:49

2 Answers 2

1
    String text="(A,X(B,C(G,H),D),X(E,F),G,H)";

    int brackets=0;
    int lastComma=0;
    List<String> parts=new ArrayList<>();
    for(int i=1;i<text.length()-1;i++)
    {
        char c=text.charAt(i);
        if(c=='(')
            brackets++;
        else if(c==')')
            brackets--;
        else if(c==',' && brackets==0)
        {
            parts.add("{"+text.substring(lastComma+1,i)+"}");
            lastComma=i;
        }
    }
    parts.add("{"+text.substring(lastComma+1,text.length()-1)+"}");

    System.out.println(parts); //[{A}, {X(B,C(G,H),D)}, {X(E,F)}, {G}, {H}]
Sign up to request clarification or add additional context in comments.

2 Comments

that's it thank you sir, one thing the last element disappeared but i will try to figure it out why
I edited my code to correct that oversight of me. Check the line after the loop.
0

As long as your string doesn't have inner nested parenthesis like your above example you could use split:

String str = "(A,X(B,C,D),X(E,F),G,H)";

String[] splited = str.substring(1, str.length()-1).split(",(?![^()]*\\))");
System.out.println(Arrays.toString(splited));

//output: [A, X(B,C,D), X(E,F), G, H]

3 Comments

unfortunately it can have nested arguments like this "(A,X(B,X(A,B),D),X(E,F),G,H)"
And what would the desired output look like for such an input?
[{A}, {X(B,X(A,B),D)}, {X(E,F)}, {G}, {H}]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.