Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java split string to get only two words

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading