Reputation: 25556
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).
Upvotes: 60
Views: 167200
Reputation: 1
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;
}
}
Upvotes: 0
Reputation: 3413
String testString = "This is a sentence";
String[] parts = testString.split(" ");
String lastWord = parts[parts.length - 1];
System.out.println(lastWord); // "sentence"
Upvotes: 22
Reputation: 726579
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
.
Upvotes: 15
Reputation: 28865
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);
}
Upvotes: 5
Reputation: 199225
String test = "This is a sentence";
String lastWord = test.substring(test.lastIndexOf(" ")+1);
Upvotes: 179
Reputation: 1174
If other whitespace characters are possible, then you'd want:
testString.split("\\s+");
Upvotes: 13