Java: Simplest way to get last word in a string
JavaStringJava Problem Overview
What is the simplest way to get the last word of a string in Java? You can assume no punctuation (just alphabetic characters and whitespace).
Java Solutions
Solution 1 - Java
String test = "This is a sentence";
String lastWord = test.substring(test.lastIndexOf(" ")+1);
Solution 2 - Java
String testString = "This is a sentence";
String[] parts = testString.split(" ");
String lastWord = parts[parts.length - 1];
System.out.println(lastWord); // "sentence"
Solution 3 - Java
Here is a way to do it using String
's built-in regex capabilities:
String lastWord = sentence.replaceAll("^.*?(\\w+)\\W*$", "$1");
The idea is to match the whole string from ^
to $
, capture the last sequence of \w+
in a capturing group 1, and replace the whole sentence with it using $1
.
Solution 4 - Java
If other whitespace characters are possible, then you'd want:
testString.split("\\s+");
Solution 5 - Java
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);
}
Solution 6 - Java
Get the last word in Kotlin:
String.substringAfterLast(" ")
Solution 7 - Java
String s="print last word";
x:for(int i=s.length()-1;i>=0;i--) {
if(s.charAt(i)==' ') {
for(int j=i+1;j<s.length();j++) {
System.out.print(s.charAt(j));
}
break x;
}
}