读取字符串直到空格然后拆分 - Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4305054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:40:19  来源:igfitidea点击:

Read String Until Space Then Split - Java

javastringsplit

提问by Luke

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.

如何在 Java 中拆分字符串?
我想读取一个字符串,直到有空格为止。
然后在空格后将其拆分为不同的字符串。

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

例如 String fullcmd =/join luke
我想将其拆分为:
String cmd = /join
String name = luke
OR
String fullcmd =/leave luke
我想将其拆分为:
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.

我确实考虑过String cmd = fullcmd.substring(0,5);
但是cmd的长度因命令而异。

采纳答案by Sean Patrick Floyd

It's easiest if you use String.split()

如果你使用它是最简单的 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

回答by darioo

Use String.split.

使用String.split

In your case, you would use

在你的情况下,你会使用

fullcmd.split(" ");

回答by gigadot

If you are parsing from command line argument, there is an apache commons cliwhich parse command line arguments into objects for you.

如果您从命令行参数进行解析,则有一个apache commons cli可以为您将命令行参数解析为对象。

回答by AlexR

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.

正如 dario 所提到的,使用String.split()。请注意,参数不是简单的分隔符而是正则表达式,因此在您的情况下,您可以说:str.split('\\s+')如果单词由多个空格分隔,则将句子拆分为单独的单词 event。