Reputation: 59
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!
Upvotes: 1
Views: 163
Reputation: 653
Or try this StringTokenizer class
StringTokenizer st = new StringTokenizer("this is a test"); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); }
Upvotes: 0
Reputation: 20231
Here a few options, sorted from easy/annoying-in-the-end to powerful/hard-to-learn
java.util.Scanner
lets you take out one token after the other, and it has some handy helpers for parsing like nextInt()
or nextFloat()
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 :)
Upvotes: 1
Reputation: 111329
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
Upvotes: 5