开发者

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

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 o开发者_高级运维n 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 are parsing from command line argument, there is an apache commons cli which parse command line arguments into objects for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜