how do I get the value of X, Y, and Z from a string "vt X,Y,Z"
views:
342answers:
3
+6
A:
As long as the format stays simple like that, I'd use
String s = "vt X, Y, Z";
String[] values = s.split("[ ,]+");
String x = values[1];
String y = values[2];
String z = values[3];
If the format has more flexibility, you'll want to look into using either a regular expression (the Pattern class) or creating a parser for it using something like ANTLR
Scott Stanchfield
2009-04-10 20:38:54
Will it work with Z? Z doesn't have a , after it.
William
2009-04-10 21:24:37
Yes William, that will work with Z... the split method takes a regex, and "[ ,]+" means "one or more, spaces OR commas" So any sequence of spaces and commas will be split on.
Tom
2009-04-10 21:26:58
A:
Regular expressions could be used for this easily, as long as your format stayed consistent in terms of whitespace and comma delimiters.
Jason Coyne
2009-04-10 20:40:37
+4
A:
I'd probably opt for a regular expression (assuming X, Y, and Z are ints
):
Pattern p = Pattern.compile("vt ([0-9]+),\\s*([0-9]+),\\s*([0-9]+)");
Matcher m = p.match(line);
if (!m.matches())
throw new IllegalArgumentException("Invalid input: " + line);
int x = Integer.parseInt(m.group(1));
int y = Integer.parseInt(m.group(2));
int z = Integer.parseInt(m.group(3));
This gives you better handling of invalid input than a simple split on the comma delimiter.
erickson
2009-04-10 20:42:23