Java が文字列が空 (null、""、" ") であると判断する 3 つの状況

受信文字列が空であるか、空文字列であるか、すべてスペースであるかを判断する方法:

方法 1: 単純な判断

/ **
   * 判断字符串是否为null 或者空串或者空格串
   *
   * @param strings 传入若干字符串
   * @return遍历传入的字符串,若有空则返回true
   * /
 public static boolean isEmpty(String ...strings){
     for(String str:strings){
         if(str == null || str.trim().length()== 0)
             return true;
}
     return false;
}        


方法 2: ツールを使用する

StringUtilsクラスの 2 つのメソッドを呼び出します。


StringUtils.isEmpty(xxx)

StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false

StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false

//-----------------------------------------------------------------------
    /**
     * <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>
     *
     * <p>NOTE: This method changed in Lang version 2.0.
     * It no longer trims the CharSequence.
     * That functionality is available in isBlank().</p>
     *
     * @param cs  the CharSequence to check, may be null
     * @return {@code true} if the CharSequence is empty or null
     * @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence)
     */
    public static boolean isEmpty(final CharSequence cs) {
        return cs == null || cs.length() == 0;
    }


if (StringUtils.isBlank(xxx)) 
 

StringUtils.isBlank(null) = true
StringUtils.isBlank("") =    true
StringUtils.isBlank(" ") =    true

StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false

//-----------------------------------------------------------------------
 
    /**
     * <p>Checks if a CharSequence is empty (""), null or whitespace only.</p>
     *
     * <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</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 only
     * @since 2.0
     * @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence)
     */
    public static boolean isBlank(final CharSequence cs) {
        final int strLen = length(cs);
        if (strLen == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if (!Character.isWhitespace(cs.charAt(i))) {
                return false;
            }
        }
        return true;

おすすめ

転載: blog.csdn.net/weixin_45987577/article/details/127241540