tags:

views:

342

answers:

3

how do I get the value of X, Y, and Z from a string "vt X,Y,Z"

+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
Will it work with Z? Z doesn't have a , after it.
William
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
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
+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
([0-9]+) if you want to support numbers with more than one digit
basszero