判空、判等、转码的StringUtil

实用字符串工具类详解
本文详细介绍了用于处理字符串的工具类StringUtil,包括字符串比较、空检查、空白检查及字符串转换等功能,提供了丰富的示例代码,便于理解和应用。

目录

1502888-20190427165316320-1855296628.jpg

StringUtil类

import java.io.UnsupportedEncodingException;

/**
 * 字符串工具
 */
public class StringUtil {


    /**
     * 比较两个字符串(大小写敏感)。
     * <pre>
     * StringUtil.equals(null, null)   = true
     * StringUtil.equals(null, "abc")  = false
     * StringUtil.equals("abc", null)  = false
     * StringUtil.equals("abc", "abc") = true
     * StringUtil.equals("abc", "ABC") = false
     * </pre>
     *
     * @param str1 要比较的字符串1
     * @param str2 要比较的字符串2
     *
     * @return 如果两个字符串相同,或者都是<code>null</code>,则返回<code>true</code>
     */
    public static boolean equals(String str1, String str2) {
        if (str1 == null) {
            return str2 == null;
        }

        return str1.equals(str2);
    }
    // Empty checks
    //-----------------------------------------------------------------------
    /**
     * <p>Checks if a CharSequence is empty ("") or null.</p>
     * <pre>
     * StringUtils.isEmpty(null)      = true
     * StringUtils.isEmpty("")        = true
     * StringUtils.isEmpty(" ")       = false
     * StringUtils.isEmpty("bob")     = false
     * StringUtils.isEmpty("  bob  ") = false
     * </pre>
     * @param cs  the CharSequence to check, may be null
     * @return {@code true} if the CharSequence is empty or null
     */
    public static boolean isEmpty(CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    /**
     * <p>Checks if a CharSequence is not empty ("") and not null.</p>
     *
     * <pre>
     * StringUtils.isNotEmpty(null)      = false
     * StringUtils.isNotEmpty("")        = false
     * StringUtils.isNotEmpty(" ")       = true
     * StringUtils.isNotEmpty("bob")     = true
     * StringUtils.isNotEmpty("  bob  ") = true
     * </pre>
     *
     * @param cs  the CharSequence to check, may be null
     * @return {@code true} if the CharSequence is not empty and not null
     */
    public static boolean isNotEmpty(CharSequence cs) {
        return !StringUtils.isEmpty(cs);
    }

    /**
     * <p>Checks if a CharSequence is whitespace, empty ("") or null.</p>
     *
     * <pre>
     * StringUtils.isBlank(null)      = true
     * StringUtils.isBlank("")        = true
     * StringUtils.isBlank(" ")       = true
     * StringUtils.isBlank("bob")     = false
     * StringUtils.isBlank("  bob  ") = false
     * </pre>
     * @param cs  the CharSequence to check, may be null
     * @return {@code true} if the CharSequence is null, empty or whitespace
     * @since 2.0
     */
    public static boolean isBlank(CharSequence cs) {
        int strLen;
        if (cs == null || (strLen = cs.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if (Character.isWhitespace(cs.charAt(i)) == false) {
                return false;
            }
        }
        return true;
    }

    /**
     * <p>Checks if a CharSequence is not empty (""), not null and not whitespace only.</p>
     *
     * <pre>
     * StringUtils.isNotBlank(null)      = false
     * StringUtils.isNotBlank("")        = false
     * StringUtils.isNotBlank(" ")       = false
     * StringUtils.isNotBlank("bob")     = true
     * StringUtils.isNotBlank("  bob  ") = true
     * </pre>
     * @param cs  the CharSequence to check, may be null
     * @return {@code true} if the CharSequence is
     *  not empty and not null and not whitespace
     */
    public static boolean isNotBlank(CharSequence cs) {
        return !StringUtils.isBlank(cs);
    }

    /**
     * @param content 需要加密串
     * @param charset 字符集
     * @return 加密后的字节数组
     */
    public static byte[] getContentBytes(String content, String charset) {
        if (StringUtils.isEmpty(charset)) {
            return content.getBytes();
        }
        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("转码过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
        }
    }

}

转载于:https://www.cnblogs.com/ranandrun/p/StringUtil.html

### Java 中 String 类型的方法 在 Java 开发中,`String` 类型的是一个非常常见的需求。以下是几种常用的 `String` 方式及其特点: #### 1. 使用 `==` 和 `""` 可以通过比较字符串是否等于字符串 (`""`) 来断其内容是否为[^1]。 ```java if (str == "") { System.out.println("字符串为"); } ``` 需要注意的是,这种方式仅能检测字符串的内容是否为字符序列,而无法处理 `null` 的情况。 --- #### 2. 使用 `.equals("")` 通过调用 `String.equals()` 方法来断字符串是否为字符串。 ```java if (str != null && str.equals("")) { System.out.println("字符串为"); } ``` 此方法同样可以用于检测字符串,但由于它依赖于实例方法调用,因此需要先确认字符串不为 `null`,否则会抛出 `NullPointerException`。 --- #### 3. 使用 `isEmpty()` 自 Java 8 起引入了更简洁的方式——`String#isEmpty()` 方法,该方法可以直接断字符串是否为字符串而不考虑 `null` 值[^3]。 ```java if (str != null && str.isEmpty()) { System.out.println("字符串为"); } ``` 注意:如果传入的对象可能为 `null`,则仍需提前校验以避免异常。 --- #### 4. 结合 `Optional` 处理潜在的 `null` 值 对于可能存在 `null` 的场景,可借助 Java 8 提供的 `Optional` 工具类简化逻辑并增强代码的安全性[^4]。 ```java import java.util.Optional; public class Main { public static void main(String[] args) { String str = null; Optional.ofNullable(str).ifPresentOrElse( s -> System.out.println("字符串非"), () -> System.out.println("字符串为或null") ); } } ``` 上述实现利用了 `Optional.ofNullable()` 静态工厂方法封装目标变量,并通过链式调用来执行不同的分支操作。 --- #### 推荐的最佳实践 综合来看,在实际项目开发过程中建议优先选用工具库中的静态辅助函数完成此类功能,例如 Apache Commons Lang 或 Spring Framework 扩展包均提供了专门针对字符串优化过的 API[^5]。 示例代码如下所示: ```java // 使用 Apache Commons Lang 库中的 StringUtils.isBlank() if (StringUtils.isBlank(str)) { System.out.println("字符串为或者全是白字符"); } // 使用 Spring Framework 提供的 org.springframework.util.StringUtils.hasText() if (!org.springframework.util.StringUtils.hasText(str)) { System.out.println("字符串为或者全是白字符"); } ``` 这些第三方框架不仅能够有效减少重复造轮子的工作量,而且经过大量测试验证具备更高的稳定性和兼容性表现。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值