What is the best way to extract the first word from a string in Java?
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.
You should be doing this
String input = "hello world, this is a line of text";
int i = input.indexOf(' ');
String word = input.substring(0, i);
String rest = input.substring(i);
The above is the fastest way of doing this task.
The simple one I used to do is
str.contains(" ") ? str.split(" ")[0] : str
Where str
is your string or text bla bla :). So, if
str
is having empty value it returns as it is.str
is having one word, it returns as it is.str
is multiple words, it extract the first word and return.
Hope this is helpful.
To simplify the above:
text.substring(0, text.indexOf(' '));
Here is a ready function:
private String getFirstWord(String text) {
int index = text.indexOf(' ');
if (index > -1) { // Check if there is more than one word.
return text.substring(0, index).trim(); // Extract first word.
} else {
return text; // Text is the first word itself.
}
}