两种解决方式:

  1. 利用String内置方法
    String的split方***根据传入的字符把String字符串分割成一个String数组,然后直接访问数组的最后一个元素ji'k
    public class Main{
     public static void main(String[] args) {
         Scanner scanner = new Scanner(System.in);
         String str = scanner.nextLine();
         String[] s = str.split(" ");
         System.out.println(s[s.length - 1].length());
     }
    }
  2. 从后往前遍历,计数
    遇到空格则停止遍历,直接输出结果
    public class Main{
    public static void main(String[] args) {
         Scanner scanner = new Scanner(System.in);
         String str = scanner.nextLine();
         int length = str.length();
         int cnt = 0;
         for(int i = length - 1; i >= 0; i--){
             if(str.charAt(i) == ' '){
                 break;
             }
             cnt++;
         }
         System.out.println(cnt);
     }
    }