Tutorial :Java string: how do I get the value of X, Y, and Z from a string “vt X,Y,Z”



Question:

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


Solution:1

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


Solution:2

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »