【问题标题】:Java equivalent of c# String.IsNullOrEmpty() and String.IsNullOrWhiteSpace()Java 等效于 c# String.IsNullOrEmpty() 和 String.IsNullOrWhiteSpace()
【发布时间】:2011-12-12 15:23:48
【问题描述】:

在 c# 中工作,我发现 String 类的两个静态方法非常有用:

我在 Java 中找不到有效的代理,有类似的吗?

其实这两种方法我都是这样翻译的:

public static boolean isNullOrEmpty(String a) {
return a == null || a.isEmpty();
} 

public static boolean isNullOrWhiteSpace(String a) {
return a == null || (a.length() > 0 && a.trim().length() <= 0);
}

这是在 Java 中翻译这些方法的最佳方式吗? 在 Java 中翻译这两种方法的最佳方式是什么?

【问题讨论】:

  • 这可能是你的答案:stackoverflow.com/q/2272169/681807
  • 您的第二个实现并不完全相同。空字符串将返回 false,而 C# 则返回 true。您可以删除a.length() &gt; 0 &amp;&amp;,它会是一样的。

标签: c# java string


【解决方案1】:

我不希望使用String.trim 来检查是否存在空白。它所做的工作比您需要的要多,因为它检查字符串的两端(即使在另一端找到非空格)并且它返回一个新的 String 对象。所以我宁愿实现一种方法来只检查空格。

所以我的建议(如果自己实现)如下:

public static boolean isNullOrEmpty(String s) {
    return s == null || s.length() == 0;
}

public static boolean isNullOrWhitespace(String s) {
    return s == null || isWhitespace(s);

}
private static boolean isWhitespace(String s) {
    int length = s.length();
    if (length > 0) {
        for (int i = 0; i < length; i++) {
            if (!Character.isWhitespace(s.charAt(i))) {
                return false;
            }
        }
        return true;
    }
    return false;
}

或者从 String.trim 的实现中获取提示,您可以使用字符比较而不是 Character.isWhitespace():

// checking for whitespace like String.trim() does
private static boolean isWhitespace(String s) {
    int length = s.length();
    if (length > 0) {
        for (int i = 0; i < length; i++) {
            if (s.charAt(i) > ' ') {
                return false;
            }
        }
        return true;
    }
    return false;
}

最后,我会考虑在每次迭代中检查字符串的两端,逐步向内。这将最大限度地减少获得答案所需的迭代次数,无论字符串的开头还是结尾是否存在空格。

private static boolean isWhitespace(String s) {
    int length = s.length();
    if (length > 0) {
        for (int start = 0, middle = length / 2, end = length - 1; start <= middle; start++, end--) {
            if (s.charAt(start) > ' ' || s.charAt(end) > ' ') {
                return false;
            }
        }
        return true;
    }
    return false;
}

【讨论】:

  • 如果字符串为空,您的实现 if IsNullOrWhitespace 将返回 false,这与 c# 的实现不匹配。这是一个实现:gist.github.com/jamiegs/5391961
  • 杰米格斯是对的。因为您使用的是 IsWhiteSpace 方法,并且您可能会争辩说 "" 不是空格而是空的,所以您可以添加一个空字符串检查。 public static boolean isNullOrWhitespace(String s) { return s == null || s == "" || isWhitespace(s); }
  • 就我个人而言,我认为 唯一 使用此实现而不是 OP 建议的原因是“trim”似乎使用了一种不太准确的方法检测空白。否则,这个答案是过度设计的。我宁愿有一个更简洁的代码而不是稍微更有效的算法(真的 - 只是稍微!)。
  • @sudocode 因为我没有做基准测试,我真的可以评论性能,但从它的外观来看,两种算法都是 O(n)。所以不确定是否有任何优化。但我完全同意,如果 OP 正在开发一个库,那么尽可能优化是有意义的。
【解决方案2】:

你总是可以通过.net反射器或其他反编译器看到c#的实现:

public static bool IsNullOrEmpty(string value)
{
  if (value != null)
    return value.Length == 0;
  else
    return true;
}

public static bool IsNullOrWhiteSpace(string value)
{
  if (value == null)
    return true;
  for (int index = 0; index < value.Length; ++index)
  {
    if (!char.IsWhiteSpace(value[index]))
      return false;
  }
  return true;
}

【讨论】:

    【解决方案3】:

    你可以这样试试

    import org.apache.commons.lang.StringUtils;
    
    public class CheckEmptyStringExample 
    {  
      public static void main(String[] args)
      {
         String string1 = "";
         String string2 = "\t\r\n";
         String string3 = " ";
         String string4 = null;
         String string5 = "Hi"; 
         System.out.println("\nString one is empty? " + StringUtils.isBlank(string1));
         System.out.println("String one is not empty? " + StringUtils.isNotBlank(string1));
         System.out.println("\nString two is empty? " +  StringUtils.isBlank(string2));
         System.out.println("String two is not empty?" + StringUtils.isNotBlank(string2));
         System.out.println("\nString three is empty?" + StringUtils.isBlank(string3));
         System.out.println("String three is not empty?" + StringUtils.isNotBlank(string3));
         System.out.println("\nString four is empty?" +  StringUtils.isBlank(string4));
         System.out.println("String four is not empty?" + StringUtils.isNotBlank(string4));
         System.out.println("\nString five is empty?" + StringUtils.isBlank(string5));
         System.out.println("String five is not empty?" + StringUtils.isNotBlank(string5)); 
      }
    }
    

    【讨论】:

      【解决方案4】:

      看看 apache commons lang 中的 StringUtils 类。

      【讨论】:

        【解决方案5】:

        如果你导入com.google.common.base.Strings,你有 Strings.isNullOrEmpty()

        isNullOrEmpty(@Nullable String string)
        

        【讨论】:

        • 这不能回答 OP 的问题,因为它不满足“isNullOrWhitespace”要求。
        【解决方案6】:

        apache.commons.lang.StringUtils 就是答案。

        isBlank()

        isEmpty()

        【讨论】:

        • StringUtils 中有什么方法?这不是一个很有帮助的答案。
        【解决方案7】:

        Apache Commons Lang 有一组非常方便的字符串实用程序:http://commons.apache.org/lang/api-release/org/apache/commons/lang3/StringUtils.html

        当然,如果您不想打扰依赖项,您的实现就足够了。

        【讨论】:

          【解决方案8】:

          JDK11 中,String 类有一个 isBlank 方法:

          如果字符串为空或仅包含空格,则返回 true 码点,否则为假。

          虽然它不检查无效性,但它肯定更接近 C# 的string.IsNullOrWhiteSpace

          你现在可以这样做了:

          var isNullOrWhiteSpace = str == null || str.isBlank();
          

          或者创建一个辅助方法:

          public static boolean isNullOrWhitespace(String s) { return s == null || str.isBlank(); }
          

          【讨论】:

            【解决方案9】:

            这应该更简单易懂。

            public static boolean isNullOrEmpty(String s) {
                return s == null || s.length() == 0;
            }
            
            public static boolean isNullOrWhitespace(String s) {
                return isNullOrEmpty(s) ? true : isNullOrEmpty(s.trim());
            }
            

            【讨论】:

              【解决方案10】:

              对于 isnullorempty:返回一个 == null || a.length == 0;
              对于 isnullorwhitespace,您必须检查每个字符,直到找到非空白字符(ascii 或 unicode)

              【讨论】:

              • 过于简洁,没有帮助
              猜你喜欢
              • 2013-11-11
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-05-23
              • 1970-01-01
              • 1970-01-01
              • 2011-06-03
              • 2010-11-30
              相关资源
              最近更新 更多