What is the best way to extract the first word from a string in Java?

The Solution to What is the best way to extract the first word from a string in Java? is


The second parameter of the split method is optional, and if specified will split the target string only N times.

For example:

String mystring = "the quick brown fox";
String arr[] = mystring.split(" ", 2);

String firstWord = arr[0];   //the
String theRest = arr[1];     //quick brown fox

Alternatively you could use the substring method of String.

~ Answered on 2011-02-21 15:44:46


Most Viewed Questions: