Reading a line up to a space, then Split - Java

How can I break a string in Java?
I would like to read the line until there is room.
Then split it on another line after a space.

eg. String fullcmd = /join luke
I would like to break it into:
Cmd = /join string
String name = luke
OR
String fullcmd = /leave luke
I would like to break it into:
String cmd = /leave
String name = luke

So that I can:

 if(cmd.equals"/join") System.out.println(name + " joined."); else if(cmd.equals"/leave" System.out.println(name + " left."); 

I really thought about doing String cmd = fullcmd.substring(0,5);
But the length of cmd depends on the command.

+6
java string split
source share
4 answers

This is easiest if you use String.split()

 String[] tokens = fullcmd.split(" "); if(tokens.length!=2){throw new IllegalArgumentException();} String command = tokens[0]; String person = tokens[1]; // now do your processing 
+15
source share

Use String.split .

In your case you should use

 fullcmd.split(" "); 
+4
source share

As already mentioned, darioo uses String.split () . Note that the argument is not a simple delimiter, but a regular expression, so in your case you can say: str.split('\\s+') , which splits your sentence into separate words if the words are separated by several spaces.

+3
source share

If you understand the command line argument, there are apache commons cli that parse command line arguments for objects for you.

+1
source share

All Articles