1
\$\begingroup\$

I want to convert string arrays with following structure:

static String[] lines = { "@1 var_decl name: testStr parent: @7", " srcp: Auto.cpp:6 " }; 

into Java objects with following structure:

class Token { String type; String name; String source; Token parent; } 

So far I'm parsing this in this way:

Token parseLines(String[] lines) { String[] firstElements = lines[0].split(" "); String[] secondElements = lines[1].split(" "); Token newToken = new Token(); newToken.type = firstElements[6]; newToken.name = firstElements[16]; String parentName = firstElements[19]; newToken.parent = getParent(parent); // find parent by name newToken.source = secondElements[26]; return newToken; } 

As you can see, this is far from elegant. How can I improve this?

\$\endgroup\$
4
  • \$\begingroup\$@Heslacher Yup, fixed.\$\endgroup\$
    – Kao
    CommentedJan 12, 2015 at 8:50
  • 1
    \$\begingroup\$Not completely check length\$\endgroup\$
    – Heslacher
    CommentedJan 12, 2015 at 8:53
  • \$\begingroup\$The code seems obviously broken in other ways too.\$\endgroup\$CommentedJan 12, 2015 at 10:43
  • \$\begingroup\$I've rewritten the whole code.\$\endgroup\$
    – Kao
    CommentedJan 13, 2015 at 9:56

1 Answer 1

1
\$\begingroup\$

My approach would start by looking something like the code below. Obviously whatever you wind up with should be in its own class/method to do the mapping from String[] to Token.

public final class Test { private static final int TYPE_COLUMN = 1; private static final int NAME_COLUMN = 3; private static final int PARENT_COLUMN = 5; private static final int SOURCE_COLUMN = 7; public static void main(final String[] args) { final String[] lines = { "@1 var_decl name: testStr parent: @7", " srcp: Auto.cpp:6 " }; final String[] values = (lines[0] + lines [1]).split("\\s+"); System.out.println(All Values:" + java.util.Arrays.toString(values)); System.out.println("Type: " + values[TYPE_COLUMN]); System.out.println("Name: " + values[NAME_COLUMN]); System.out.println("Parent: " + getParent(values[PARENT_COLUMN])); System.out.println("Source: " + values[SOURCE_COLUMN]); } private static String getParent(final String parentId) { return "Parent"; } } 
\$\endgroup\$

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.