Read String Until Space Then Split - Java
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
/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);
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
Use String.split.
In your case, you would use
fullcmd.split(" ");
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.
If you are parsing from command line argument, there is an apache commons cli which parse command line arguments into objects for you.
精彩评论