How to get the Length of the Last Word in a String using Java

The challenge

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.

If the last word does not exist, return 0.

Note: A word is defined as a maximal substring consisting of non-space characters only.


Input: "Hello World"
Output: 5

The solution in Java

class Solution {
    public int lengthOfLastWord(String s) {
        // catch edge case of blank input
        if (s.length()<=0) return 0;
        // split into words
        String[] words = s.split("\\s+");
        // if one or less words, then return the length of the trimmed string
        if (words.length<=1) return s.trim().length();
        // get the alst word
        String lastWord = words[words.length-1];
        // return the last word's length
        return lastWord.length();
Notify of
Inline Feedbacks
View all comments