如何检查字符串是否不为空且不为空?
public void doStuff(String str)
{
if (str != null && str != "**here I want to check the 'str' is empty or not**")
{
/* handle empty string */
}
/* ... */
}
如何检查字符串是否不为空且不为空?
public void doStuff(String str)
{
if (str != null && str != "**here I want to check the 'str' is empty or not**")
{
/* handle empty string */
}
/* ... */
}
那么isEmpty()呢?
if(str != null && !str.isEmpty())
请务必&&
按此顺序使用 的部分,因为如果第一部分失败,java 将不会继续评估第二部分&&
,从而确保您不会从str.isEmpty()
ifstr
为 null 得到空指针异常。
请注意,它仅在 Java SE 1.6 之后可用。您必须检查str.length() == 0
以前的版本。
也忽略空格:
if(str != null && !str.trim().isEmpty())
(因为 Java 11str.trim().isEmpty()
可以简化为str.isBlank()
也将测试其他 Unicode 空白)
包装在一个方便的功能中:
public static boolean empty( final String s ) {
// Null-safe, short-circuit evaluation.
return s == null || s.trim().isEmpty();
}
变成:
if( !empty( str ) )
我喜欢将 Apache commons-lang用于这类事情,尤其是StringUtils实用程序类:
import org.apache.commons.lang.StringUtils;
if (StringUtils.isNotBlank(str)) {
...
}
if (StringUtils.isBlank(str)) {
...
}
只需在此处添加 Android:
import android.text.TextUtils;
if (!TextUtils.isEmpty(str)) {
...
}
添加到@BJorn 和@SeanPatrickFloyd Guava 的方法是:
Strings.nullToEmpty(str).isEmpty();
// or
Strings.isNullOrEmpty(str);
Commons Lang 有时更具可读性,但我一直在慢慢地更多地依赖 Guava,而且有时 Commons Lang 会让人感到困惑isBlank()
(比如什么是空白)。
Guava 的 Commons Lang 版本isBlank
是:
Strings.nullToEmpty(str).trim().isEmpty()
我会说不允许""
(空)AND null
的代码是可疑的并且可能存在错误,因为它可能无法处理所有不允许的情况null
(尽管对于 SQL,我可以理解为 SQL/HQL 很奇怪''
)。
str != null && str.length() != 0
或者
str != null && !str.equals("")
或者
str != null && !"".equals(str)
注意:第二次检查(第一种和第二种选择)假设 str 不为空。没关系,只是因为第一次检查是这样做的(如果第一次检查是否为假,Java 不会进行第二次检查)!
重要提示:不要将 == 用于字符串相等。== 检查指针是否相等,而不是值。两个字符串可以位于不同的内存地址(两个实例)但具有相同的值!
我知道的几乎每个库都定义了一个名为StringUtils
, StringUtil
or的实用程序类StringHelper
,它们通常包含您正在寻找的方法。
我个人最喜欢的是Apache Commons / Lang,在StringUtils类中,您可以同时获得
(第一个检查字符串是否为空或空,第二个检查它是否为空、空或仅空格)
Spring、Wicket 和许多其他库中也有类似的实用程序类。如果你不使用外部库,你可能想在你自己的项目中引入一个 StringUtils 类。
更新:很多年过去了,这些天我建议使用Guava的Strings.isNullOrEmpty(string)
方法。
这对我有用:
import com.google.common.base.Strings;
if (!Strings.isNullOrEmpty(myString)) {
return myString;
}
如果给定字符串为 null 或为空字符串,则返回 true。
考虑使用 nullToEmpty 规范化您的字符串引用。如果这样做,您可以使用 String.isEmpty() 代替此方法,并且您也不需要像 String.toUpperCase 这样的特殊 null 安全形式的方法。或者,如果您想规范化“在另一个方向”,将空字符串转换为 null,您可以使用 emptyToNull。
java-11中有一个新方法:String#isBlank
如果字符串为空或仅包含空白代码点,则返回 true,否则返回 false。
jshell> "".isBlank()
$7 ==> true
jshell> " ".isBlank()
$8 ==> true
jshell> " ! ".isBlank()
$9 ==> false
这可以与Optional
检查字符串是否为空或为空
boolean isNullOrEmpty = Optional.ofNullable(str).map(String::isBlank).orElse(true);
怎么样:
if(str!= null && str.length() != 0 )
使用 Apache StringUtils 的 isNotBlank 方法,例如
StringUtils.isNotBlank(str)
只有当 str 不为 null 且不为空时,它才会返回 true。
根据输入返回真或假
Predicate<String> p = (s)-> ( s != null && !s.isEmpty());
p.test(string);
如果您不想包含整个库;只需包含您想要的代码。您必须自己维护它;但这是一个非常简单的功能。这里是从commons.apache.org复制的
/**
* <p>Checks if a String 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 str the String to check, may be null
* @return <code>true</code> if the String is null, empty or whitespace
* @since 2.0
*/
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
有点太晚了,但这里有一种功能性的检查方式:
Optional.ofNullable(str)
.filter(s -> !(s.trim().isEmpty()))
.ifPresent(result -> {
// your query setup goes here
});
为了完整性:如果您已经在使用 Spring 框架,则StringUtils提供该方法
org.springframework.util.StringUtils.hasLength(String str)
返回:如果 String 不为 null 并且有长度,则返回 true
以及方法
org.springframework.util.StringUtils.hasText(String str)
返回:如果 String 不为 null、长度大于 0 且不包含空格,则返回 true
test 等于一个空字符串,并且在相同的条件下为 null:
if(!"".equals(str) && str != null) {
// do stuff.
}
NullPointerException
如果 str 为 null则不抛出,因为Object.equals()
如果 arg 为 则返回 false null
。
另一个构造str.equals("")
会抛出 dreaded NullPointerException
。有些人可能会认为使用字符串文字作为调用对象的错误形式,equals()
但它可以完成工作。
简单的解决方案:
private boolean stringNotEmptyOrNull(String st) {
return st != null && !st.isEmpty();
}
正如上面的 seanizer 所说,Apache StringUtils 非常适合这一点,如果你要包含 guava,你应该执行以下操作;
public List<Employee> findEmployees(String str, int dep) {
Preconditions.checkState(StringUtils.isNotBlank(str), "Invalid input, input is blank or null");
/** code here **/
}
我还建议您按名称而不是索引来引用结果集中的列,这将使您的代码更易于维护。
我制作了自己的实用函数来一次检查多个字符串,而不是使用一个充满if(str != null && !str.isEmpty && str2 != null && !str2.isEmpty)
. 这是功能:
public class StringUtils{
public static boolean areSet(String... strings)
{
for(String s : strings)
if(s == null || s.isEmpty)
return false;
return true;
}
}
所以我可以简单地写:
if(!StringUtils.areSet(firstName,lastName,address)
{
//do something
}
您可以使用 StringUtils.isEmpty(),如果字符串为 null 或为空,则结果为 true。
String str1 = "";
String str2 = null;
if(StringUtils.isEmpty(str)){
System.out.println("str1 is null or empty");
}
if(StringUtils.isEmpty(str2)){
System.out.println("str2 is null or empty");
}
将导致
str1 为空或为空
str2 为 null 或为空
如果您使用 Java 8 并希望拥有更多的函数式编程方法,您可以定义一个Function
管理控件的方法,然后您可以apply()
在需要时重用它。
来实践,你可以定义Function
为
Function<String, Boolean> isNotEmpty = s -> s != null && !"".equals(s)
然后,您可以通过简单地调用该apply()
方法来使用它:
String emptyString = "";
isNotEmpty.apply(emptyString); // this will return false
String notEmptyString = "StackOverflow";
isNotEmpty.apply(notEmptyString); // this will return true
如果您愿意,您可以定义 aFunction
来检查 是否String
为空,然后用 否定它!
。
在这种情况下,Function
将如下所示:
Function<String, Boolean> isEmpty = s -> s == null || "".equals(s)
然后,您可以通过简单地调用该apply()
方法来使用它:
String emptyString = "";
!isEmpty.apply(emptyString); // this will return false
String notEmptyString = "StackOverflow";
!isEmpty.apply(notEmptyString); // this will return true
使用Java 8 Optional,您可以:
public Boolean isStringCorrect(String str) {
return Optional.ofNullable(str)
.map(String::trim)
.map(string -> !str.isEmpty())
.orElse(false);
}
在此表达式中,您还将处理String
由空格组成的 s。
我会根据您的实际需要建议 Guava 或 Apache Commons。检查我的示例代码中的不同行为:
import com.google.common.base.Strings;
import org.apache.commons.lang.StringUtils;
/**
* Created by hu0983 on 2016.01.13..
*/
public class StringNotEmptyTesting {
public static void main(String[] args){
String a = " ";
String b = "";
String c=null;
System.out.println("Apache:");
if(!StringUtils.isNotBlank(a)){
System.out.println(" a is blank");
}
if(!StringUtils.isNotBlank(b)){
System.out.println(" b is blank");
}
if(!StringUtils.isNotBlank(c)){
System.out.println(" c is blank");
}
System.out.println("Google:");
if(Strings.isNullOrEmpty(Strings.emptyToNull(a))){
System.out.println(" a is NullOrEmpty");
}
if(Strings.isNullOrEmpty(b)){
System.out.println(" b is NullOrEmpty");
}
if(Strings.isNullOrEmpty(c)){
System.out.println(" c is NullOrEmpty");
}
}
}
结果:
Apache:
a 是空白
b 是空白
c 是空白
Google:
b 是 NullOrEmpty
c 是 NullOrEmpty
简单地说,也忽略空白:
if (str == null || str.trim().length() == 0) {
// str is empty
} else {
// str is not empty
}
如果您使用的是 Spring Boot,那么下面的代码将完成这项工作
StringUtils.hasLength(str)
如果你使用 Spring 框架,那么你可以使用方法:
org.springframework.util.StringUtils.isEmpty(@Nullable Object str);
此方法接受任何 Object 作为参数,将其与 null 和空字符串进行比较。因此,对于非空非字符串对象,此方法将永远不会返回 true。
检查对象中的所有字符串属性是否为空(而不是在 java 反射 api 方法之后的所有字段名称上使用 !=null
private String name1;
private String name2;
private String name3;
public boolean isEmpty() {
for (Field field : this.getClass().getDeclaredFields()) {
try {
field.setAccessible(true);
if (field.get(this) != null) {
return false;
}
} catch (Exception e) {
System.out.println("Exception occurred in processing");
}
}
return true;
}
如果所有 String 字段值为空,此方法将返回 true,如果 String 属性中存在任何一个值,则返回 false
我遇到过必须检查“null”(作为字符串)必须被视为空的情况。空格和实际的null也必须返回 true。我终于确定了以下功能...
public boolean isEmpty(String testString) {
return ((null==testString) || "".equals((""+testString).trim()) || "null".equals((""+testString).toLowerCase()));
}
如果您需要验证您的方法参数,您可以使用以下简单方法
public class StringUtils {
static boolean anyEmptyString(String ... strings) {
return Stream.of(strings).anyMatch(s -> s == null || s.isEmpty());
}
}
例子:
public String concatenate(String firstName, String lastName) {
if(StringUtils.anyBlankString(firstName, lastName)) {
throw new IllegalArgumentException("Empty field found");
}
return firstName + " " + lastName;
}
要检查字符串是否不为空,您可以检查它是否为空,null
但这并不能说明带有空格的字符串。您可以使用str.trim()
修剪所有空格然后链接.isEmpty()
以确保结果不为空。
if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }
考虑下面的例子,我在 main 方法中添加了 4 个测试用例。当您遵循上述注释片段时,三个测试用例将通过。
public class EmptyNullBlankWithNull {
public static boolean nullEmptyBlankWithNull(String passedStr) {
if (passedStr != null && !passedStr.trim().isEmpty() && !passedStr.trim().equals("null")) {
// TODO when string is null , Empty, Blank
return true;
}else{
// TODO when string is null , Empty, Blank
return false;
}
}
public static void main(String[] args) {
String stringNull = null; // test case 1
String stringEmpty = ""; // test case 2
String stringWhiteSpace = " "; // test case 3
String stringWhiteSpaceWithNull = " null"; // test case 4
System.out.println("TestCase result:------ "+nullEmptyBlankWithNull(stringWhiteSpaceWithNull));
}
}
但是测试用例 4 将返回 true(它在 null 之前有空格),这是错误的:
String stringWhiteSpaceWithNull = " null"; // test case 4
我们必须添加以下条件以使其正常工作:
!passedStr.trim().equals("null")
处理字符串中的 null 的更好方法是,
str!=null && !str.equalsIgnoreCase("null") && !str.isEmpty()
简而言之,
str.length()>0 && !str.equalsIgnoreCase("null")
import android.text.TextUtils;
if (!TextUtils.isEmpty(str)||!str.equalsIgnoreCase("") {
...
}