60

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).

3
  • related: stackoverflow.com/questions/1181969/… Commented Jan 12, 2011 at 19:03
  • 3
    Title says "fastest", questions asks for "simplest". Please clarify. Commented Jan 12, 2011 at 20:42
  • 1
    Fastest and simplest for coding and reading. Execution time is irrelevant. As an aside, having different wording is better for search purposes although the discrepancy was unintentional. Commented Jan 12, 2011 at 21:49

7 Answers 7

180
String test =  "This is a sentence";
String lastWord = test.substring(test.lastIndexOf(" ")+1);
Sign up to request clarification or add additional context in comments.

4 Comments

Needs a +1 there and fails on a single word.
One line is nice since I will be using it in Velocity template code. Could be combined with a regular expession to account for other characters like JST's solution.
Actually this is better, it already accounts for a single word: String lastWord = test.substring(test.lastIndexOf(" ")+1);
what if a sentence has some punctuation at the end? "This is a sentence?!"
22
String testString = "This is a sentence";
String[] parts = testString.split(" ");
String lastWord = parts[parts.length - 1];
System.out.println(lastWord); // "sentence"

7 Comments

This is the solution I probably would have come up with on my own, not bad, but a one-liner would be better.
When you say "fastest," do you mean shortest in code or fastest to execute? This could be made into a one liner, but it wouldn't execute any faster and would be much harder to read.
I did not say "fastest", I said "simplest", by which I meant a combination of brevity and ease of understanding.
@Muhd If it were me, I would think the above is easiest to read. Then again, this is also the solution I immediately came up with. @OscarRyz's solution is also simple to read, so it comes down to personal preference.
@Dave Probably mine, is not easier to read anymore for I have added a check in case the string it self is the last word.
|
15

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.

Demo.

3 Comments

This one is solid gold
Neat because it's a one liner
Edge case: This fails in right-to-left languages (ex. Hebrew). @OscarRyz substring method still works. ideone.com/MacH0s
13

If other whitespace characters are possible, then you'd want:

testString.split("\\s+");

Comments

5

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);
}

Comments

1

Get the last word in Kotlin:

String.substringAfterLast(" ")

Comments

0
  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;
         }
     }

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.