Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read String Until Space Then Split - Java

Tags:

java

string

split

How can I split a string in Java?
I would like to read a string until there is a space.
Then split it into a different string after the space.

e.g. String fullcmd = /join luke
I would like to split it into:
String cmd = /join
String name = luke
OR
String fullcmd = /leave luke
I would like to split 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 did think about doing String cmd = fullcmd.substring(0,5);
But cmd's length varies depending on the command.

like image 229
Luke Avatar asked Nov 29 '10 15:11

Luke


3 Answers

It's 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
like image 103
Sean Patrick Floyd Avatar answered Sep 22 '22 13:09

Sean Patrick Floyd


Use String.split.

In your case, you would use

fullcmd.split(" ");
like image 25
darioo Avatar answered Sep 19 '22 13:09

darioo


As is was mentioned by darioo use String.split(). Pay attention that the argument is not a simple delimiter but regular expression, so in your case you can say: str.split('\\s+') that splits your sentence into separate words event if the words are delimited by several spaces.

like image 24
AlexR Avatar answered Sep 21 '22 13:09

AlexR