\$\begingroup\$
\$\endgroup\$
4
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?
asked Jan 12, 2015 at 8:45
-
\$\begingroup\$ @Heslacher Yup, fixed. \$\endgroup\$Kao– Kao2015年01月12日 08:50:50 +00:00Commented Jan 12, 2015 at 8:50
-
1\$\begingroup\$ Not completely check length \$\endgroup\$Heslacher– Heslacher2015年01月12日 08:53:55 +00:00Commented Jan 12, 2015 at 8:53
-
\$\begingroup\$ The code seems obviously broken in other ways too. \$\endgroup\$200_success– 200_success2015年01月12日 10:43:47 +00:00Commented Jan 12, 2015 at 10:43
-
\$\begingroup\$ I've rewritten the whole code. \$\endgroup\$Kao– Kao2015年01月13日 09:56:09 +00:00Commented Jan 13, 2015 at 9:56
1 Answer 1
\$\begingroup\$
\$\endgroup\$
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";
}
}
answered Jan 14, 2015 at 15:48
lang-java