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?
CodePudding user response:
You can also use substring:
String string = "hello world bye moon";
String stringTwo = string.substring(0, string.indexOf(' ', string.indexOf(' ') 1));
System.out.println(stringTwo);
CodePudding user response:
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