1. Overview
In this short tutorial, we'll learn how to get the last word of a String in Java using two approaches.
2. Using the split() Method
The split() instance method from the String class splits the string based on the provided regular expression. It's an overloaded method and returns an array of String.
Let's consider an input String, “I wish you a bug-free day”.
As we have to get the last word of a string, we'll be using space (” “) as a regular expression to split the string.
We can tokenize this String using the split() method and get the last token, which will be our result:
public String getLastWordUsingSplit(String input) {
String[] tokens = input.split(" ");
return tokens[tokens.length - 1];
}
This will return “day”, which is the last word of our input string.
Note that if the input String has only one word or has no space in it, the above method will simply return the same String.
3. Using the substring() method
The substring() method of the String class returns the substring of a String. It's an overloaded method, where one of the overloaded versions accepts the beginIndex and returns all the characters in the String after the given index.
We'll also use the lastIndexOf() method from the String class. It accepts a substring and returns the index within this string of the last occurrence of the specified substring. This specified substring is again going to be a space (” “) in our case.
Let's combine substring() and lastIndexOf to find the last word of an input String:
public String getLastWordUsingSubString(String input) {
return input.substring(input.lastIndexOf(" ") + 1);
}
If we pass the same input String as before, “I wish you a bug-free day”, our method will return “day”.
Again, note that if the input String has only one word or has no space in it, the above method will simply return the same String.
4. Conclusion
In summary, we have seen two methods to get the last word of a String in Java.