Home > Mobile >  Java split string to get only two words
Java split string to get only two words

Time:08-08

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
  • Related