String trim方法及trim方法重写

java中String的trim方法只能去除字符串头尾的半角空格,而我们所做的系统往往是用户输入为中文的系统。因此需要我们重写trim方法。

/**
     * <p>Checks if a String is whitespace, empty ("") or null.</p>
     * <p>
     * <pre>
     * StringUtils.isBlank(null)      = true
     * StringUtils.isBlank("")        = true
     * StringUtils.isBlank(" ")       = true
     * StringUtils.isBlank("bob")     = false
     * StringUtils.isBlank("  bob  ") = false
     * </pre>
     *
     * @param str the String to check, may be null
     * @return <code>true</code> if the String is null, empty or whitespace
     * @since 2.0
     */
    public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }
/**
     * 执行trim操作(包含全角和半角的空格;)
     *
     * @param str 字符串
     * @return 结果字符串
     */
    public static String trim(String str) {
        if (isBlank(str)) {//判断字符串是否为空或长度为零或是一段空格,上面有该函数代码
            return "";
        } else {
            str = str.trim();// 去掉半角符号的空格
            while (str.startsWith(" ")) {//该空格为全角空格
                str = str.substring(1, str.length()).trim();
                if (isBlank(str)) {
                    return "";
                }
            }
            while (str.endsWith(" ")) { // 该空格为全角空格
                str = str.substring(0, str.length() - 1).trim();
                if (isBlank(str)) {
                    return "";
                }
            }
        }
        return str;
    }



您的帮助是我莫大的鼓励!喜欢的话可以扫描左侧二维码随意打赏哈~支付宝微信都可以,欢迎看看我的其他文章~

在这里谢谢已经支持的朋友们,打赏有价,支持与鼓励无价!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值