- 时间限制:1秒空间限制:32768K
- 算法知识视频讲解
题目描述
计算字符串最后一个单词的长度,单词以空格隔开。
输入描述:
一行字符串,非空,长度小于5000。
输出描述:
整数N,最后一个单词的长度。
输入例子:
hello world
输出例子:
5
思路:切割字符串,把最后一个字符串的长度输出即可。
import java.util.Scanner;
public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in);String str = sc.nextLine();String[] s = str.split("\\s+");if(s.length==0){System.out.println(0);}else{System.out.println(s[s.length-1].length());}}
}