如何在 Java 中将字符串除以空 space

How to divide string by empty space in Java

所以,我有以下情况:

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

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

所以,我知道用户会输入这样的内容:love cats and dogs。 我希望第一个词(在本例中为 love)始终在 String 中,其他所有在 String 中。我怎样才能做到尽可能简单?

简单:

int splitIndex = line.indexOf(" ");
String first = line.substring(0, splitIndex);
String second = line.substring(splitIndex + 1);
String line = "love cats and dogs";
// split into 2 parts
String[] parts = line.split(" ",2);

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