The length of the last word

Description: You are given a string S, which consists of several words separated by Spaces. Returns the length of the last word in the string. If no last word exists, return 0.

A word is the largest substring that consists of only letters and does not contain any space characters.

See the LeetCode website for an example.

Source: LeetCode Link: https://leetcode-cn.com/probl… Copyright belongs to collar network. Commercial reprint please contact the official authorization, non-commercial reprint please indicate the source.

Solution 1: Use the lastIndexOf method

First of all, with
trim()Method will be
sRemove the space before and after, and determine if
sIf not, there is only one word
sThe length of the; If it contains, use
lastIndexOf()Methods to obtain
sThe position of the last space in the
substring()Methods intercept
sReturns the length of the last word in the

public class LeetCode_058 {
    public static int lengthOfLastWord(String s) {
        s = s.trim();
        if (!s.contains(" ")) {
            return s.length();
        }
        int lastIndexOfSpace = s.lastIndexOf(" ");
        return s.substring(lastIndexOfSpace, s.length() - 1).length();
    }

    public static void main(String[] args) {
        System.out.println(lengthOfLastWord("Hello World"));
    }
}

【 Daily Message 】
If they don’t have a smile on their face, show them your smile. Face every day with a smile.