一种简单的遍历判断方式:

  1. 首先,定义计数器count,然后对字符串进行遍历
  2. if语句判断是否遍历过程中有空格' '
  3. 如果有空格,break结束遍历
  4. 输出count计数器,得到答案
import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String str = sc.nextLine();
            int count = 0;
            for(int i = str.length() - 1; i >= 0; i--){
                if(str.charAt(i) != ' '){
                    count++;
                }else{
                    break;
                }
            }
            System.out.print(count);
        }
    }
}