如何检查一个字符串不为空?

4
if(string.equals(""))
{

}

如何检查字符串是否不为空?

if(!string.equals(""))
{

}

4
如何检查一个字符串是否等于 null? - Yaneeve
不重要的是,string.length() == 0 可能比等于 "" 更好。 - MeBigFatGuy
13个回答

42

通过 if (string != null) 可以检查是否为null

如果想要检查是否为null或为空 - 您需要 if (string != null && !string.isEmpty())

我更喜欢使用 commons-langStringUtils.isNotEmpty(..)


2
再次为 StringUtils 点赞。我们每个人都应该花几分钟时间阅读 Apache Commons 可以为我们做什么! - Pablo Grisafi

5
你可以使用以下代码实现:
 if (string != null) {

 }

2

检查 null 值的方法如下:

string != null

你的示例实际上是检查空字符串。

你可以像这样将两个组合起来:

if (string != null && !string.equals("")) { ...

但是null和empty是两个不同的概念。


2

以上答案已经很充分了,我只是将其整理成一个简单的类。如果你只需要这些函数或几个帮助函数,编写自己的简单类是最简单的方法,同时可以保持可执行文件的大小不变。 Commons-lang 也是不错的选择。

public class StringUtils {

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

  public static boolean isNotEmpty(String s) {
    return !isEmpty(s);
  }
}

1

使用TextUtils方法。

TextUtils.isEmpty(str) :如果字符串为null或长度为0,则返回true。 参数:str要检查的字符串。 返回值:如果str为null或长度为零,则返回true。

if(TextUtils.isEmpty(str)){
    // str is null or lenght is 0
}

TextUtils类源代码
isEmpty方法:
 public static boolean isEmpty(CharSequence str) {
        if (str == null || str.length() == 0)
            return true;
        else
            return false;
    }

您可以在此处找到:http://developer.android.com/reference/android/text/TextUtils.html - Kishan Vaghela

1
if(str != null && !str.isEmpty())

请确保按照这个顺序使用 && 的各个部分,因为如果第一个 && 的部分失败,Java 将不会继续评估第二个部分,从而确保如果 str 为空,则不会从 str.isEmpty() 得到空指针异常。请注意,此功能仅适用于 Java SE 1.6 及更高版本。在之前的版本中,您必须检查 str.length() == 0 或 str.equals("")。

0

检查字符串的最佳方法是:

import org.apache.commons.lang3.StringUtils;

if(StringUtils.isNotBlank(string)){
....
}

来自文档

isBlank(CharSequence cs) :

检查CharSequence是否为空(“”),null或仅包含空格。


你应该指定它的库全名,Commons,并更加具体地说明方法的行为。在我看来,你应该稍微改进一下答案。问候 - Fabiano Tarlao
1
@FabianoTarlao 没问题,朋友,已经更新了答案! - aayoustic

0

您可以使用 Predicate 及其新方法(自 Java 11 起)Predicate::not

您可以编写代码来检查字符串是否不为空且非空:

Predicate<String> notNull = Predicate.not(Objects::isNull);
Predicate<String> notEmptyString = Predicate.not(String::isEmpty);
Predicate<String> isNotEmpty = notNull.and(notEmptyString);

然后你可以进行测试:

System.out.println(isNotEmpty.test(""));      // false
System.out.println(isNotEmpty.test(null));    // false
System.out.println(isNotEmpty.test("null"));  // true

0

正如大家所说的,你必须检查(string!= null),在对象中你正在测试内存指针。

因为每个对象都通过一个内存指针来识别,所以在测试其他任何东西之前,你必须先检查对象是否为空指针,所以:

(string!= null &&!string.equals(“”))是好的

(!string.equals(“”)&& string!= null)可能会导致空指针异常。

如果您不关心尾随空格,您可以在equals()之前始终使用trim()

就像 " " 和 "" 给你同样的结果


0
尝试使用来自com.google.common.base.Strings的Strings.isNullOrEmpty("")方法,该方法返回布尔值并检查null和空字符串。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接