You can do that with StringUtils
(from Apache Commons Lang). It avoids index-magic, so it's easier to understand. Unfortunately substringAfterLast
returns empty string when there is no separator in the input string so we need the if
statement for that case.
public static String getLastWord(String input) {
String wordSeparator = " ";
boolean inputIsOnlyOneWord = !StringUtils.contains(input, wordSeparator);
if (inputIsOnlyOneWord) {
return input;
}
return StringUtils.substringAfterLast(input, wordSeparator);
}