由于字符串中可能存在空格,所以可输入可用 in.nextLine(),然后用java中的split方法,将字符串以空格进行分割,分割后得到字符串数组,数组中最后一个元素的值既为所求单词长度。
下面给出代码:
import java.util.*;
public class Main{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
String str = in.nextLine();//输入一行
String s[]= str.split(" ");//采用正则表达式进行分割
System.out.println(s[s.length-1].length());
}
}