题目描述

1. 题目描述

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

https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da?tpId=37&tqId=21224&tPage=1&rp=&ru=/ta/huawei&qru=/ta/huawei/question-ranking

2. 示例代码

import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNext())
        {
            String line = scanner.nextLine();
            int index = line.lastIndexOf(' ');
            String word = line.substring(index+1);
            System.out.println(word.length());
        }
    }
}