donemanuel
donemanuel

Reputation: 59

How to take parts from string in Java?

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

Answers (3)

Damian0o
Damian0o

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

kritzikratzi
kritzikratzi

Reputation: 20231

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 :)

Upvotes: 1

Joni
Joni

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

Related Questions