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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With