题解 | #字符串最后一个单词的长度#

1、暴力处理,根据空格来调用split切割字符串,这里可以写" " 或者通过正则"\\s+ ",正则是为了,如果有多个空格,例如"123 456   789"的情况,依然可以切割成三个字符串
然后得到一个数组,数组的最后一位就是需求中的单词,获取单词的长度即可

import java.util.Scanner;  
public static void main(String[] args){
      Scanner sc = new Scanner(System.in);
      String str = sc.nextLine();
      String[] s = str.split(" "); //正则表达式实用性更强( str.split("\\s+"))
      int length = s[s.length - 1].length();
      System.out.println(length);
  }




2、将输入的string,倒序遍历,如果char等于空格,那就break,并且在for循环里面计数。

  
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.charAt(i)==' ') { // 或者 if (str.substring(i, i + 1).equals(" ")) {
              break;
          }
          count++;
      }
      System.out.println(count);
  }



全部评论

相关推荐

点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务