1

How will you proceed the following string:

[p('WHITE'),p('GREEN'),p('GREEN','RED'),p('GREEN','YELLOW'),p('GREEN','YELLOW','RED')]

to get a List of Nodes as suggested in the answers.

8
  • To get a list of which strings? The values between p(' and ')? Unique or non unique? Commented Nov 29, 2010 at 22:29
  • That doesn't look like a string. Is it enclosed in double quotes? Commented Nov 29, 2010 at 22:29
  • What is the expected output that you are looking for? Can you give the exact output you want for your example that you have given. Commented Nov 29, 2010 at 22:30
  • Why should this not be a string? It is a "sequence of characters", which is often called a "string" for short. Commented Nov 29, 2010 at 22:31
  • Yes it is enclosed in double quotes. And yes to have the values between p(' and') that are unique Commented Nov 29, 2010 at 22:32

1 Answer 1

4

It depends on how complex the expressions can get. I would definitely write a proper parser for it, since only then can I be confident to have done it properly. Plus, I will parse the string into an abstract syntax tree so that at the end I will automatically have a nicely modeled tree of objects:

class Node { ... }

class StringLiteral extends Node {
  public String getValue() { ... }
}

class Term extends Node {
  public String getName() { ... }
  public int getArity() { ... }
  public Node getArgument(int index) { ... }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yes you are right. But now how will you parse the string to get these nodes ??
The basic idea is to write a Parser class that has one method per syntactical element that you are interested in. I would call them List<Node> parseArray(), Term parseTerm(), StringLiteral parseStringLiteral(), Node parseExpression(). The implementation of parseArray would look roughly like read('[']); while (next() != ']') { parseExpression(); } read(']');. The methods basically contain sequences of these operations or large switch statements, which decide what to parse next, depending on the next character from the input.

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.