Muhd
Muhd

Reputation: 25556

Java: Simplest way to get last word in a string

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

Answers (7)

Sapan Nn
Sapan Nn

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

Weiyi
Weiyi

Reputation: 1933

Get the last word in Kotlin:

String.substringAfterLast(" ")

Upvotes: 1

Dave McClelland
Dave McClelland

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

Sergey Kalinichenko
Sergey Kalinichenko

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.

Demo.

Upvotes: 15

palacsint
palacsint

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

OscarRyz
OscarRyz

Reputation: 199225

String test =  "This is a sentence";
String lastWord = test.substring(test.lastIndexOf(" ")+1);

Upvotes: 179

JST
JST

Reputation: 1174

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

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

Upvotes: 13

Related Questions