If you have an String, how can you get the first two words.
Example
String string = "hello world bye moon";
String stringTwo;
String[] newStringArray;
newStringArray = string.split(" ");
stringTwo = newStringArray[0] + " " + newStringArray[1];
System.out.println(stringTwo);
Do you know a short efficient way?
>Solution :
As an alternative to String#split(), you could use a regex replacement approach:
String string = "hello world bye moon";
String firstTwo = string.replaceAll("(\\w+ \\w+).*", "$1");
System.out.println(firstTwo); // hello world