华为od德科面试数据算法解析 2022-5-29 计算字符串最后一个单词的长度

题目解析:

一、计算字符串最后一个单词的长度,单词以空格隔开。

输入描述:
输入一行,代表要计算的字符串,非空,长度小于5000。

输出描述:
输出一个整数,表示输入字符串最后一个单词的长度。

public class Main{
   public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        //排除最后一位是空格的情况
        if (str.charAt(str.length() - 1) == ' ') {
            str = str.substring(0, str.length() - 1);
        }

        String[] split = str.split(" ");
        int length = split[split.length - 1].length();
        System.out.println(length);
    }
    }

猜你喜欢

转载自blog.csdn.net/qq_38735017/article/details/125496685