如何在Java中用空格分割字符串

时间:2015-12-30 18:57:48

标签: java bufferedreader readline

所以,我有以下情况:

private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

String line= reader.readLine();
String first = ?
String second = ?

所以,我知道用户会输入这样的东西:喜欢猫和狗。 我希望第一个单词(在本例中为love)始终在String中,其他所有内容在String中。我怎样才能尽可能简单?

2 个答案:

答案 0 :(得分:1)

String line = "love cats and dogs";
// split into 2 parts
String[] parts = line.split(" ",2);

String first = parts[0];
String second = parts[1];

答案 1 :(得分:0)

简单地:

int splitIndex = line.indexOf(" ");
String first = line.substring(0, splitIndex);
String second = line.substring(splitIndex + 1);