Java: Simplest way to get last word in a string

JavaString

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

Demo.

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMuhdView Question on Stackoverflow
Solution 1 - JavaOscarRyzView Answer on Stackoverflow
Solution 2 - JavaDave McClellandView Answer on Stackoverflow
Solution 3 - JavaSergey KalinichenkoView Answer on Stackoverflow
Solution 4 - JavaJSTView Answer on Stackoverflow
Solution 5 - JavapalacsintView Answer on Stackoverflow
Solution 6 - Javali2View Answer on Stackoverflow
Solution 7 - JavaSapan NnView Answer on Stackoverflow