1

So, I have the following situation:

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

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

So, I know that user will enter something like this: love cats and dogs. I want that the first word (in this case love) is always in String first and everything else in String second. How can I do it as simple as possible?

MyNameIsNemo
  • 71
  • 1
  • 2
  • 9
  • Possible duplicate of [split string only on first instance - java](http://stackoverflow.com/questions/18462826/split-string-only-on-first-instance-java) – riddle_me_this Dec 30 '15 at 19:55

2 Answers2

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

String first = parts[0];
String second = parts[1];
Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
0

Simply:

int splitIndex = line.indexOf(" ");
String first = line.substring(0, splitIndex);
String second = line.substring(splitIndex + 1);
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118