题解 | #字符串最后一个单词的长度#

字符串最后一个单词的长度

https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da

import java.util.*;

public class Main {

    /**
    1. 从输入流中获取用户输入。
    2. 使用 hasNextLine 获取一整行的输入。
    3. 逆向循环字符串,当遇到空格时,返回字符串长度与当前位置的差。
     */
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String strs = "";
        while (scan.hasNextLine()) {
            strs = scan.nextLine();
        }
        scan.close();

        System.out.println(getLastStrLen(strs));
    }

    private static int getLastStrLen(String strs) {
        for (int i = strs.length()-1; i >= 0; i--) {
            if (strs.charAt(i) == ' ') {
                return strs.length() - i - 1; // -1 因为要把空格长度排除
            }
        }
        return strs.length();
    }
}

全部评论

相关推荐

06-25 16:25
梧州学院 Java
愿汐_:项目介绍那么长,然而你做了啥就一句话?
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 14:08
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务