在 Java 中检查非空字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16394787/
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
Checking for a not null, not blank String in Java
提问by partha
I am trying to check if a Java String is not null
, not empty and not whitespace.
我正在尝试检查 Java String 是否不是null
,不是空也不是空白。
In my mind, this code should have been quite up for the job.
在我看来,这段代码应该非常适合这项工作。
public static boolean isEmpty(String s) {
if ((s != null) && (s.trim().length() > 0))
return false;
else
return true;
}
As per documentation, String.trim()
should work thus:
根据文档,String.trim()
应该这样工作:
Returns a copy of the string, with leading and trailing whitespace omitted.
If this
String
object represents an empty character sequence, or the first and last characters of character sequence represented by thisString
object both have codes greater than'\u0020'
(the space character), then a reference to thisString
object is returned.
返回字符串的副本,省略前导和尾随空格。
如果这个
String
对象表示一个空字符序列,或者这个对象表示的字符序列的第一个和最后一个字符的String
代码都大于'\u0020'
(空格字符),则String
返回对该对象的引用。
However, apache/commons/lang/StringUtils.java
does it a little differently.
然而,apache/commons/lang/StringUtils.java
它有点不同。
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;
}
As per documentation, Character.isWhitespace()
:
根据文档,Character.isWhitespace()
:
Determines if the specified character is white space according to Java. A character is a Java whitespace character if and only if it satisfies one of the following criteria:
- It is a Unicode space character (
SPACE_SEPARATOR
,LINE_SEPARATOR
, orPARAGRAPH_SEPARATOR
) but is not also a non-breaking space ('\u00A0'
,'\u2007'
,'\u202F'
).- It is
'\t'
, U+0009 HORIZONTAL TABULATION.- It is
'\n'
, U+000A LINE FEED.- It is
'\u000B'
, U+000B VERTICAL TABULATION.- It is
'\f'
, U+000C FORM FEED.- It is
'\r'
, U+000D CARRIAGE RETURN.- It is
'\u001C'
, U+001C FILE SEPARATOR.- It is
'\u001D'
, U+001D GROUP SEPARATOR.- It is
'\u001E'
, U+001E RECORD SEPARATOR.- It is
'\u001F'
, U+001F UNIT SEPARATOR.
根据Java判断指定字符是否为空格。一个字符是 Java 空白字符当且仅当它满足以下条件之一:
- 它是一个 Unicode 空格字符(
SPACE_SEPARATOR
、LINE_SEPARATOR
、 或PARAGRAPH_SEPARATOR
),但也不是一个不间断空格('\u00A0'
、'\u2007'
、'\u202F'
)。- 它是
'\t'
,U+0009 水平制表。- 它是
'\n'
,U+000A 换行符。- 它是
'\u000B'
,U+000B 垂直制表。- 它是
'\f'
,U+000C 表单馈送。- 它是
'\r'
,U+000D 回车。- 它是
'\u001C'
,U+001C 文件分隔符。- 它是
'\u001D'
,U+001D 组分隔符。- 它是
'\u001E'
,U+001E 记录分隔符。- 它是
'\u001F'
,U+001F 单位分隔符。
If I am not mistaken - or might be I am just not reading it correctly - the String.trim()
should take away any of the characters that are being checked by Character.isWhiteSpace()
. All of them see to be above '\u0020'
.
如果我没有记错——或者可能是我没有正确阅读它——String.trim()
应该删除任何正在检查的字符Character.isWhiteSpace()
。他们一个个都看在了上面'\u0020'
。
In this case, the simpler isEmpty
function seems to be covering all the scenarios that the lengthier isBlank
is covering.
在这种情况下,较简单的isEmpty
函数似乎涵盖了较长的函数所涵盖的所有场景isBlank
。
- Is there a string that will make the
isEmpty
andisBlank
behave differently in a test case? - Assuming there are none, is there any other consideration because of which I should choose
isBlank
and not useisEmpty
?
- 是否有一个字符串会使
isEmpty
和isBlank
在测试用例中表现不同? - 假设没有,是否还有其他考虑因素我应该选择
isBlank
而不使用isEmpty
?
For those interested in actually running a test, here are the methods and unit tests.
对于那些对实际运行测试感兴趣的人,这里是方法和单元测试。
public class StringUtil {
public static boolean isEmpty(String s) {
if ((s != null) && (s.trim().length() > 0))
return false;
else
return true;
}
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;
}
}
And unit tests
和单元测试
@Test
public void test() {
String s = null;
assertTrue(StringUtil.isEmpty(s)) ;
assertTrue(StringUtil.isBlank(s)) ;
s = "";
assertTrue(StringUtil.isEmpty(s)) ;
assertTrue(StringUtil.isBlank(s));
s = " ";
assertTrue(StringUtil.isEmpty(s)) ;
assertTrue(StringUtil.isBlank(s)) ;
s = " ";
assertTrue(StringUtil.isEmpty(s)) ;
assertTrue(StringUtil.isBlank(s)) ;
s = " a ";
assertTrue(StringUtil.isEmpty(s)==false) ;
assertTrue(StringUtil.isBlank(s)==false) ;
}
Update: It was a really interesting discussion - and this is why I love Stack Overflow and the folks here. By the way, coming back to the question, we got:
更新:这是一个非常有趣的讨论 - 这就是为什么我喜欢 Stack Overflow 和这里的人们。顺便说一下,回到这个问题,我们得到:
- A program showing which all characters will make the behave differently. The code is at https://ideone.com/ELY5Wv. Thanks @Dukeling.
- A performance related reason for choosing the standard
isBlank()
. Thanks @devconsole. - A comprehensive explanation by @nhahtdh. Thanks mate.
- 一个程序,显示哪些字符会使行为不同。代码位于https://ideone.com/ELY5Wv。谢谢@Dukeling。
- 选择标准的与性能相关的原因
isBlank()
。谢谢@devconsole。 - @nhahtdh 的综合解释。谢了哥们。
回答by Maroun
The purpose of the two standardmethods is to distinguish between this two cases:
两种标准方法的目的是区分这两种情况:
org.apache.common.lang.StringUtils.isBlank(" ")
(will return true).
org.apache.common.lang.StringUtils.isBlank(" ")
(将返回true)。
org.apache.common.lang.StringUtils.isEmpty(" ")
(will return false).
org.apache.common.lang.StringUtils.isEmpty(" ")
(将返回false)。
Your custom implementation of isEmpty()
will return true.
您的自定义实现isEmpty()
将返回true。
UPDATE:
更新:
org.apache.common.lang.StringUtils.isEmpty()
is used to find if the String is length 0 or null.org.apache.common.lang.StringUtils.isBlank()
takes it a step forward. It not only checks if the String is length 0 or null, but also checks if it is only a whitespace string.
org.apache.common.lang.StringUtils.isEmpty()
用于查找字符串的长度是否为 0 或 null。org.apache.common.lang.StringUtils.isBlank()
向前迈进了一步。它不仅会检查 String 的长度是否为 0 或 null,还会检查它是否只是一个空白字符串。
In your case, you're trimming the String in yourisEmpty
method. The only difference that can occur now can't occur (the case you gives it " "
) because you're trimmingit (Removing the trailing whitespace - which is in this case is like removing allspaces).
在你的情况,你修剪的字符串的isEmpty
方法。现在可能发生的唯一区别不会发生(您给它的情况" "
),因为您正在修剪它(删除尾随空格 - 在这种情况下就像删除所有空格)。
回答by devconsole
I would choose isBlank()
over isEmpty()
because trim()
creates a new String object that has to be garbage collected later. isBlank()
on the other hand does not create any objects.
我会选择isBlank()
,isEmpty()
因为trim()
创建了一个新的 String 对象,稍后必须对其进行垃圾回收。isBlank()
另一方面不创建任何对象。
回答by Lukas Eichler
You could take a look at JSR 303 Bean Validtion wich contains the Annotatinos @NotEmpty
and @NotNull
. Bean Validation is cool because you can seperate validation issues from the original intend of the method.
您可以查看包含 Annotatinos@NotEmpty
和@NotNull
. Bean Validation 很酷,因为您可以将验证问题与方法的原始意图分开。
回答by nhahtdh
Is there a string that will make the
isEmpty
andisBlank
behave differently in a test case?
是否有一个字符串会使
isEmpty
和isBlank
在测试用例中表现不同?
Note that Character.isWhitespace
can recognize Unicode characters and return true
for Unicode whitespace characters.
注意Character.isWhitespace
可以识别 Unicode 字符并返回true
Unicode 空白字符。
Determines if the specified character is white space according to Java. A character is a Java whitespace character if and only if it satisfies one of the following criteria:
It is a Unicode space character (
SPACE_SEPARATOR
,LINE_SEPARATOR
, orPARAGRAPH_SEPARATOR
) but is not also a non-breaking space ('\u00A0'
,'\u2007'
,'\u202F'
).
[...]
根据Java判断指定字符是否为空格。一个字符是 Java 空白字符当且仅当它满足以下条件之一:
它是一个 Unicode 空格字符(
SPACE_SEPARATOR
、LINE_SEPARATOR
、 或PARAGRAPH_SEPARATOR
),但也不是一个不间断空格('\u00A0'
、'\u2007'
、'\u202F'
)。
[...]
On the other hand, trim()
method would trim all control characters whose code points are below U+0020 and the space character (U+0020).
另一方面,trim()
方法将修剪所有代码点低于 U+0020 和空格字符 (U+0020) 的控制字符。
Therefore, the two methods would behave differently at presence of a Unicode whitespace character. For example: "\u2008"
. Orwhen the string contains control characters that are not consider whitespace by Character.isWhitespace
method. For example: "\002"
.
因此,当存在 Unicode 空白字符时,这两种方法的行为会有所不同。例如:"\u2008"
。或者当字符串包含不按Character.isWhitespace
方法考虑空格的控制字符时。例如:"\002"
。
If you were to write a regular expression to do this (which is slower than doing a loop through the string and check):
如果您要编写一个正则表达式来执行此操作(这比循环遍历字符串并检查要慢):
isEmpty()
would be equivalent to.matches("[\\x00-\\x20]*")
isBlank()
would be equivalent to.matches("\\p{javaWhitespace}*")
isEmpty()
将相当于.matches("[\\x00-\\x20]*")
isBlank()
将相当于.matches("\\p{javaWhitespace}*")
(The isEmpty()
and isBlank()
method both allow for null
String reference, so it is not exactly equivalent to the regex solution, but putting that aside, it is equivalent).
(isEmpty()
andisBlank()
方法都允许null
String 引用,所以它并不完全等同于正则表达式解决方案,但把它放在一边,它是等同的)。
Note that \p{javaWhitespace}
, as its name implied, is Java-specific syntax to access the character class defined by Character.isWhitespace
method.
请注意\p{javaWhitespace}
,正如其名称所暗示的那样,是 Java 特定的语法,用于访问Character.isWhitespace
方法定义的字符类。
Assuming there are none, is there any other consideration because of which I should choose
isBlank
and not useisEmpty
?
假设没有,是否还有其他考虑因素我应该选择
isBlank
而不使用isEmpty
?
It depends. However, I think the explanation in the part above should be sufficient for you to decide. To sum up the difference:
这取决于。但是,我认为上面部分的解释应该足以让您做出决定。总结一下区别:
isEmpty()
will consider the string is empty if it contains only control characters1below U+0020 and space character (U+0020)isBlank
will consider the string is empty if it contains only whitespace characters as defined byCharacter.isWhitespace
method, which includes Unicode whitespace characters.
isEmpty()
如果字符串仅包含U+0020 下方的控制字符1和空格字符 (U+0020),则将认为该字符串为空isBlank
如果字符串仅包含Character.isWhitespace
方法定义的空白字符,则将认为该字符串为空,其中包括 Unicode 空白字符。
1There is also the control character at U+007F DELETE
, which is not trimmed by trim()
method.
1 处还有控制符U+007F DELETE
,不是trim()
方法修整的。
回答by arjunsekar1991
<%
System.out.println(request.getParameter("userName")+"*");
if (request.getParameter("userName").trim().length() == 0 | request.getParameter("userName") == null) { %>
<jsp:forward page="HandleIt.jsp" />
<% }
else { %>
Hello ${param.userName}
<%} %>
回答by Ancel Litto
Why can't you simply use a nested ternary operator to achieve this.Please look into the sample code
public static void main(String[] args)
{
String s = null;
String s1="";
String s2="hello";
System.out.println(" 1 "+check(s));
System.out.println(" 2 "+check(s1));
System.out.println(" 3 "+check(s2));
}
public static boolean check(String data)
{
return (data==null?false:(data.isEmpty()?false:true));
}
为什么不能简单地使用嵌套的三元运算符来实现这一点。请查看示例代码
public static void main(String[] args)
{
String s = null;
String s1="";
String s2="hello";
System.out.println(" 1 "+check(s));
System.out.println(" 2 "+check(s1));
System.out.println(" 3 "+check(s2));
}
public static boolean check(String data)
{
return (data==null?false:(data.isEmpty()?false:true));
}
and the output is as follows
输出如下
1 false 2 false 3 true
1 假 2 假 3 真
here the 1st 2 scenarios returns false (i.e null and empty)and the 3rd scenario returns true
这里第 2 个场景返回 false(即 null 和空),第 3 个场景返回 true
回答by Laurent
This simple code will do enough:
这个简单的代码就足够了:
public static boolean isNullOrEmpty(String str) {
return str == null || str.trim().equals("");
}
And the unit tests:
和单元测试:
@Test
public void testIsNullOrEmpty() {
assertEquals(true, AcdsUtils.isNullOrEmpty(""));
assertEquals(true, AcdsUtils.isNullOrEmpty((String) null));
assertEquals(false, AcdsUtils.isNullOrEmpty("lol "));
assertEquals(false, AcdsUtils.isNullOrEmpty("HallO"));
}
回答by Nicolas Henneaux
With Java 8, you could also use the Optional capability with filtering. To check if a string is blank, the code is pure Java SE without additional library. The following code illustre a isBlank() implementation.
使用 Java 8,您还可以使用带有过滤的 Optional 功能。要检查字符串是否为空,代码是纯 Java SE,没有额外的库。以下代码说明了 isBlank() 实现。
String.trim() behaviour
String.trim() 行为
!Optional.ofNullable(tocheck).filter(e -> e != null && e.trim().length() > 0).isPresent()
StringUtils.isBlank() behaviour
StringUtils.isBlank() 行为
Optional.ofNullable(toCheck)
.filter(e ->
{
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;
})
.isPresent()