给定由大写,小写字母和空格组成的字符串,返回最后一个单词的长度。
如果不存在最后一个单词,返回0
注意:
“单词”是指不包含空格符号的字符串
例如:
s = “hello World”, 那么返回的结果是5
格式:
第一行输入字符串s,然后输出s中最后一个单词的长度。
import java.util.Scanner;
import java.util.NoSuchElementException;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
String str;
try{
str=sc.nextLine();
}catch(NoSuchElementException e){
System.out.print(0);
return;
}
str=str.trim();
int a=str.lastIndexOf(" ");
if(a==-1)
System.out.print(str.length());
else
System.out.print(str.length()-a-1);
}
}