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

字符串最后一个单词的长度

http://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da

华为机试

HJ1 字符串最后一个单词的长度

描述:计算字符串最后一个单词的长度,单词以空格隔开,字符串长度小于5000。
思路如下:

  1. 首先判断字符串是否为空;
  2. 其次去除字符串首尾两边的空字符串String.trim();
  3. 再次判断字符串是否为空;
  4. 利用String.split("[\s]+")来分割字符串,可以以任意数量的空格分隔字符串;
  5. 返回最后一个单词的长度。

代码如下:

import java.util.*;

public class Main {
    public static int getLength(String s) {
        if (s == null || s.length() == 0) return 0;
        s = s.trim();
        if (s == null || s.length() == 0) return 0;
        String[] strs = s.split("[\\s]+");
        return strs[strs.length - 1].length();
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        System.out.println(getLength(s));
    }
}
全部评论

相关推荐

白火同学:能。我当初应届沟通了1200,收简历50,面试10左右吧,加油投吧
点赞 评论 收藏
分享
评论
2
8
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务