1

I have a small program like a console that allows input of commands trough JTextField.

I have a lot of commands written in with input being converted to a string > and if a command has like ping an IP attribute (ping 192.168.1.1) I substring 5 (ping ), but now when I want several attributes like (command atr1 art22 atr333 art4444) and I would get

String command = "command"; //I can make this one
String attribute1 = "atr1"; //I can make this one
String attribute2 = "atr22";
String attribute3 = "atr333";

and so on, but so it would give me no matter length that attribute... Because I could accomplish everything with substring, but then it would have length defined!

1
  • 3
    Have you tried string.split(" ");?
    – assylias
    Jun 20, 2013 at 12:18

3 Answers 3

5

You can use String.split:

String cmd = "command atr1 art22 atr333 art4444";
String[] parts = cmd.split(" ");

The split method permits using a regular expression. This is useful for example if the amount of whitespace varies:

String cmd = "command        atr1   art22 atr333     art4444";
String[] parts = cmd.split(" +"); // split by spans of one or more spaces
2
  • How do I then extract string parts from this String[] parts?
    – donemanuel
    Jun 20, 2013 at 12:22
  • String [] is an array of String, just loop through the array or select just the string you want with the index. Jun 20, 2013 at 12:22
1

Here a few options, sorted from easy/annoying-in-the-end to powerful/hard-to-learn

  • "your command pattern".split( " " ) gives you an array of strings
  • java.util.Scanner lets you take out one token after the other, and it has some handy helpers for parsing like nextInt() or nextFloat()
  • a command line parser library, like commons cli. those are a bit of work to learn, but they have the upside of solving some other problems you will be facing shortly :)

p.s. to generally find more help on the internet the search term you are looking for is "java parsing command line arguments", thats pretty much what you're trying to do, in case you didn't know :)

0

Or try this StringTokenizer class

 StringTokenizer st = new StringTokenizer("this is a test");
     while (st.hasMoreTokens()) {
         System.out.println(st.nextToken());
     }

1
  • 1
    The StringTokenizer is a remainder from the old java days, it was superseded by String.split( " " ) and more recently further improved with java.util.Scanner. Jun 20, 2013 at 12:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.