Java 一步检查字符串的空值和空值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1913280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:49:29  来源:igfitidea点击:

One step check for null value & emptiness of a string

javastring

提问by EugeneP

I have a setter method.

我有一个 setter 方法。

Then when another (say generate) method is run, I need to check the value of my fields. So in the case of String property, I need to know if it contains the value or if it was not set. So it may be null, "" or something meaningful, there are 3 possibilities. And it is rather boring to check first for a null value :

然后当另一个(比如生成)方法运行时,我需要检查我的字段的值。因此,在 String 属性的情况下,我需要知道它是否包含该值或是否未设置。所以它可能为空、"" 或其他有意义的东西,有 3 种可能性。首先检查空值很无聊:

if (s != null)

then for an empty String

然后为空字符串

if (!s.isEmpty())

is there a one-step check here? You can tell me that I can initialize my String field with an empty String. [ IS IT COMMON? ] But what if someone passes a null value to the setter method setS? so do we always have to check if the Object value is null or not before doing something with that object?

这里有一步检查吗?您可以告诉我,我可以使用空字符串初始化我的 String 字段。[ 这很常见吗?] 但是,如果有人将空值传递给 setter 方法 setS 呢?那么在对该对象执行某些操作之前,我们是否总是必须检查该对象的值是否为空?

Well, yes a setter method can check it's values and also a getter method can return a non-null value if the field is null. But is it the only solution? It 's too much work in getters & setters for a programmer to do!

嗯,是的,setter 方法可以检查它的值,如果字段为空,getter 方法也可以返回非空值。但这是唯一的解决方案吗?对于程序员来说,getter 和 setter 方面的工作太多了!

回答by Joel

Commons library, StringUtils.isBlank()or StringUtils.isEmtpy().

公共库,StringUtils.isBlank()StringUtils.isEmtpy()

isEmpty is equivalent to

isEmpty 相当于

s == null || s.length() == 0

isBlank is equivalent to

isBlank 等价于

s == null || s.trim().length() == 0

回答by DerMike

In the jakarta commons there is a StringUtils.isEmpty(String).

在雅加达公地有一个 StringUtils.isEmpty(String)。

回答by Grumpy

try this

尝试这个

if(s){

如果(s){

}

}

回答by Ahmed Rezk

if(s != null && !s.isEmpty()){
// this will work even if 's' is NULL
}

回答by Emad Aghayi

use org.apache.commons.lang.StringUtils, the method StringUtils.isNotBlankcheck both nullity and emptiness.

使用org.apache.commons.lang.StringUtils,方法StringUtils.isNotBlank检查空值和空值。

回答by Sophia Price

Add maven dependency for com.google.guava

com.google.guava添加 maven 依赖

Then in your code:

然后在你的代码中:

import com.google.common.base.Strings;

if(!Strings.isNullOrEmpty(s)) {
  // Do stuff here
}

回答by Noah

If you are doing android development, you can use:

如果你在做android开发,你可以使用:

TextUtils.isEmpty (CharSequence str) 

Added in API level 1 Returns true if the string is null or 0-length.

在 API 级别 1 中添加 如果字符串为空或长度为 0,则返回 true。