Thursday, April 28, 2011

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

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

From stackoverflow
  • 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

    William : Will it work with Z? Z doesn't have a , after it.
    Tom : 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.
  • Regular expressions could be used for this easily, as long as your format stayed consistent in terms of whitespace and comma delimiters.

  • 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.

    basszero : ([0-9]+) if you want to support numbers with more than one digit

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.