描述

计算字符串最后一个单词的长度,单词以空格隔开,字符串长度小于5000。(注:字符串末尾不以空格为结尾)

输入描述:

输入一行,代表要计算的字符串,非空,长度小于5000。

输出描述:

输出一个整数,表示输入字符串最后一个单词的长度。

  • ifor天下第一

     public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        int length = str.length();
        int count = 0;
        for (int i = length - 1; i >= 0; i--) {
    // 或者 if (str.substring(i, i + 1).equals(" ")) {
            if (str.charAt(i)==' ') {
                break;
            }
            count++;
        }
        System.out.println(count);
    }
    通过for循环倒叙遍历,计算长度(基本语法)
  • 哎呦不错

    public  static void  main(String [] args) throws Exception{      
          Scanner scanner=new Scanner(System.in);
          String word=scanner.nextLine();
          System.out.println(word.substring(word.lastIndexOf(" ")+1).length());
       }
    通过substring截取最后一个单词,计算长度(API玩的溜)
  • 秀儿

      public static void main(String[] args) {
          Scanner sc = new Scanner(System.in);
          String str = sc .nextLine();
          String trim = str.trim();
          int lastIndexOf = trim.lastIndexOf(" ");
          System.out.println(trim.length() - lastIndexOf - 1);
      }
    通过最后一个空格和整个字符长度的差,得出最后一个单词的长度。(数学课代表)