如何检查我的字符串是否等于 null?
仅当我的字符串具有有意义的值时,我才想执行某些操作。所以,我尝试了这个。
if (!myString.equals("")) {
doSomething
}
以及这个
if (!myString.equals(null)) {
doSomething
}
和这个
if ( (!myString.equals("")) && (!myString.equals(null))) {
doSomething
}
以及这个
if ( (!myString.equals("")) && (myString!=null)) {
doSomething
}
和这个
if ( myString.length()>0) {
doSomething
}
在所有情况下我的程序doSomething
尽管事实上我的字符串是空的。它等于null
。那么,这有什么问题呢?
添加:
我找到了问题的原因。该变量被声明为字符串,因此分配给该变量的 null
被转换为 "null"
!因此, if (!myString.equals("null"))
有效。
I want to perform some action ONLY IF my string has a meaningful value. So, I tried this.
if (!myString.equals("")) {
doSomething
}
and this
if (!myString.equals(null)) {
doSomething
}
and this
if ( (!myString.equals("")) && (!myString.equals(null))) {
doSomething
}
and this
if ( (!myString.equals("")) && (myString!=null)) {
doSomething
}
and this
if ( myString.length()>0) {
doSomething
}
And in all cases my program doSomething
in spite on the fact that my string IS EMPTY. It equals to null
. So, what is wrong with that?
ADDED:
I found the reason of the problem. The variable was declared as a string and, as a consequence, null
assigned to this variable was transformed to "null"
! So, if (!myString.equals("null"))
works.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(28)
作为进一步的评论,您应该了解
equals
合约中的这个术语:来自
Object.equals(Object)
:与
null
比较的方法是使用x == null
和x != null
。此外,如果
x == null
,x.field
和x.method()
会抛出NullPointerException
。As further comment, you should be aware of this term in the
equals
contract:From
Object.equals(Object)
:The way to compare with
null
is to usex == null
andx != null
.Moreover,
x.field
andx.method()
throwsNullPointerException
ifx == null
.如果
myString
为null
,则调用myString.equals(null)
或myString.equals("")
将失败并出现NullPointerException
。您不能对 null 变量调用任何实例方法。首先检查 null ,如下所示:
这利用 短路评估 来不尝试如果
myString
未通过 null 检查,则.equals
。If
myString
isnull
, then callingmyString.equals(null)
ormyString.equals("")
will fail with aNullPointerException
. You cannot call any instance methods on a null variable.Check for null first like this:
This makes use of short-circuit evaluation to not attempt the
.equals
ifmyString
fails the null check.Apache commons
StringUtils.isNotEmpty
是最好的方法。Apache commons
StringUtils.isNotEmpty
is the best way to go.如果 myString 实际上为 null,则对该引用的任何调用都将失败并出现空指针异常 (NPE)。
从 java 6 开始,使用 #isEmpty 而不是长度检查(在任何情况下都不要使用检查创建新的空字符串)。
顺便说一句,如果像您一样与字符串文字进行比较,则会反转该语句,以便不必进行空检查,即
代替:
If myString is in fact null, then any call to the reference will fail with a Null Pointer Exception (NPE).
Since java 6, use #isEmpty instead of length check (in any case NEVER create a new empty String with the check).
Incidentally if comparing with String literals as you do, would reverse the statement so as not to have to have a null check, i.e,
instead of :
正在运行!!!
已更新
对于 Kotlin,我们通过以下方式检查字符串是否为空
WORKING !!!!
Updated
For Kotlin we check if the string is null or not by following
您需要检查
myString
对象是否为null
:You need to check that the
myString
object isnull
:如果您的字符串为空,这样的调用应该抛出 NullReferenceException:
myString.equals(null)
但无论如何,我认为这样的方法就是您想要的:
然后在您的代码中,您可以执行以下操作:
If your string is null, calls like this should throw a NullReferenceException:
myString.equals(null)
But anyway, I think a method like this is what you want:
Then in your code, you can do things like this:
我鼓励使用现有的实用程序,或创建您自己的方法:
然后在需要时使用它:
如上所述,||和&&操作者短路。这意味着一旦他们能够确定自己的价值,他们就会停止。因此,如果 (string == null) 为 true,则不需要计算长度部分,因为表达式始终为 true。与 && 类似,如果左侧为 false,则表达式始终为 false,无需进一步求值。
作为补充说明,使用长度通常比使用 .equals 更好。性能稍好一些(不多),并且不需要创建对象(尽管大多数编译器可能会对此进行优化)。
I would encourage using an existing utility, or creating your own method:
Then just use it when you need it:
As noted above, the || and && operators short circuit. That means as soon as they can determine their value they stop. So if (string == null) is true, the length part does not need to be evaluated, as the expression would always be true. Likewise with &&, where if the left side is false, the expression is always false and need not be evaluated further.
As an additional note, using length is generally a better idea than using .equals. The performance is slightly better (not much), and doesn't require object creation (though most compilers might optimize this out).
尝试,
Try,
顺便说一句,如果您要进行大量字符串操作,那么有一个很棒的 Spring 类,其中包含各种有用的方法:
http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/util/StringUtils.html
Incidently, if you are doing much string manipulation, there's a great Spring class with all sorts of useful methods:
http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/util/StringUtils.html
每次我必须处理字符串(几乎每次)时,我都会停下来想知道哪种方法才是检查空字符串的最快方法。当然, string.Length == 0 检查应该是最快的,因为 Length 是一个属性,除了检索属性的值之外不应该进行任何处理。但后来我问自己,为什么会有 String.Empty?我告诉自己,检查 String.Empty 应该比检查长度更快。好吧,我最终决定测试一下。我编写了一个小型 Windows 控制台应用程序,它告诉我对 1000 万次重复进行某项检查需要多长时间。我检查了 3 个不同的字符串:一个 NULL 字符串、一个空字符串和一个“”字符串。我使用了 5 种不同的方法: String.IsNullOrEmpty()、str == null、str == null || str == String.Empty,str == null || str == "", str == null || str.length == 0。结果如下:
根据这些结果,平均检查
str == null
是最快的,但可能并不总是能得到我们想要的结果。如果 str = String.Empty
或str = ""
,则结果为 false。然后你有 2 个并列第二位:String.IsNullOrEmpty()
和str == null || str.length == 0
。由于String.IsNullOrEmpty()
看起来更好并且更容易(更快)编写,因此我建议使用它而不是其他解决方案。Every time i have to deal with strings (almost every time) I stop and wonder which way is really the fastest way to check for an empty string. Of course the string.Length == 0 check should be the fastest since Length is a property and there shouldn't be any processing other than retrieving the value of the property. But then I ask myself, why is there a String.Empty? It should be faster to check for String.Empty than for length, I tell myself. Well i finnaly decided to test it out. I coded a small Windows Console app that tells me how long it takes to do a certain check for 10 million repitions. I checked 3 different strings: a NULL string, an Empty string, and a "" string. I used 5 different methods: String.IsNullOrEmpty(), str == null, str == null || str == String.Empty, str == null || str == "", str == null || str.length == 0. Below are the results:
According to these results, on average checking for
str == null
is the fastest, but might not always yield what we're looking for.if str = String.Empty
orstr = ""
, it results in false. Then you have 2 that are tied in second place:String.IsNullOrEmpty()
andstr == null || str.length == 0
. SinceString.IsNullOrEmpty()
looks nicer and is easier (and faster) to write I would recommend using it over the other solution.我会做这样的事情:
I'd do something like this:
我一直在使用
StringUtil.isBlank(string)
它测试字符串是否为空: null、emtpy 或只有空格。
所以这是迄今为止最好的,
这是文档中的原始方法
I been using
StringUtil.isBlank(string)
It tests if a string is blank: null, emtpy, or only whitespace.
So this one is the best so far
Here is the orignal method from the docs
对我来说,在 Java 中检查字符串是否具有任何有意义的内容的最佳方法是:
首先检查字符串是否为
null
以避免NullPointerException
,然后修剪所有空格字符以避免检查只有空格的字符串,最后检查修剪后的字符串是否不为空,即长度是否为 0。For me the best check if a string has any meaningful content in Java is this one:
First you check if the string is
null
to avoidNullPointerException
and then you trim all space characters to avoid checking strings that only have whitespaces and finally you check if the trimmed string is not empty, i.e has length 0.这应该有效:
如果没有,那么 myString 可能有一个您不期望的值。尝试像这样打印出来:
使用“+”符号包围字符串将显示其中是否存在您没有考虑到的额外空格。
This should work:
If not, then myString likely has a value that you are not expecting. Try printing it out like this:
Using the '+' symbols to surround the string will show you if there is extra whitespace in there that you're not accounting for.
if(str.isEmpty() || str==null){
做你想做的事
}
if(str.isEmpty() || str==null){
do whatever you want
}
好吧,这就是 Java 中数据类型的工作原理。 (请原谅我的英语,我可能没有使用正确的词汇。
你必须区分其中两个。基本数据类型和普通数据类型。基本数据类型几乎构成了现有的一切。
例如,有所有数字、字符、布尔值等。
普通数据类型或复杂数据类型就是其他一切。
字符串是一个字符数组,因此是一种复杂的数据类型。
您创建的每个变量实际上都是内存中值的指针。
例如:
变量“s”不包含字符串。它是一个指针。该指针指向内存中的变量。
当您调用 System.out.println(anyObject) 时,将调用该对象的 toString() 方法。如果它没有从 Object 覆盖
toString
,它将打印指针。例如:
“@”后面的所有内容都是指针。这只适用于复杂的数据类型。原始数据类型直接保存在它们的指针中。所以实际上没有指针,而是直接存储值。
例如:
在这种情况下 i 不存储指针。我将存储整数值 123(以字节 ofc 为单位)。
好的,让我们回到
==
运算符。它总是比较指针,而不是比较内存中指针位置处保存的内容。
示例:
这两个字符串都有不同的指针。然而 String.equals(String other) 会比较内容。您可以使用“==”运算符来比较原始数据类型,因为具有相同内容的两个不同对象的指针是相等的。
Null 表示指针为空。默认情况下,空原始数据类型为 0(对于数字)。然而,任何复杂对象的 Null 都意味着该对象不存在。
问候
Okay this is how datatypes work in Java. (You have to excuse my English, I am prob. not using the right vocab.
You have to differentiate between two of them. The base datatypes and the normal datatypes. Base data types pretty much make up everything that exists.
For example, there are all numbers, char, boolean etc.
The normal data types or complex data types is everything else.
A String is an array of chars, therefore a complex data type.
Every variable that you create is actually a pointer on the value in your memory.
For example:
the variable "s" does NOT contain a String. It is a pointer. This pointer points on the variable in your memory.
When you call
System.out.println(anyObject)
, thetoString()
method of that object is called. If it did not overridetoString
from Object, it will print the pointer.For example:
Everything behind the "@" is the pointer. This only works for complex data types. Primitive datatypes are DIRECTLY saved in their pointer. So actually there is no pointer and the values are stored directly.
For example:
i does NOT store a pointer in this case. i will store the integer value 123 (in byte ofc).
Okay so lets come back to the
==
operator.It always compares the pointer and not the content saved at the pointer's position in the memory.
Example:
This both String have a different pointer. String.equals(String other) however compares the content. You can compare primitive data types with the '==' operator because the pointer of two different objects with the same content is equal.
Null would mean that the pointer is empty. An empty primitive data type by default is 0 (for numbers). Null for any complex object however means, that object does not exist.
Greetings
我在android中遇到了这个问题,我使用这种方式(为我工作):
但是在java代码中我使用:
并且:
I had this problem in android and i use this way (Work for me):
But in java code I use :
And :
我更喜欢使用:
阅读StringUtils.isBlank() vs String.isEmpty()。
I prefer to use:
Read StringUtils.isBlank() vs String.isEmpty().
在 Android 中,您可以使用
TextUtils
中的实用程序方法isEmpty
进行检查,isEmpty(CharSequence str)
方法检查两个条件,对于null< /code> 和长度。
In Android you can check this with utility method
isEmpty
fromTextUtils
,isEmpty(CharSequence str)
method check both condition, fornull
and length.如果您在 Android 中工作,那么您可以使用简单的 TextUtils 类。
检查以下代码:
这是代码的简单用法。答案可能会重复。但为您提供单一且简单的检查很简单。
If you are working in Android then you can use the simple TextUtils class.
Check the following code:
This is simple usage of code. Answer may be repeated. But is simple to have single and simple check for you.
我总是这样使用:
或者您可以将其复制到您的项目中:
然后像这样调用它:
如果为空或 null 它将返回 true。
b=true
如果为空或 null或当它为空时,你可以使用try catch和catch。
I always use like this:
or you can copy this to your project:
and just call it like :
it will return true if is empty or null.
b=true
if is empty or nullor you can use try catch and catch when it is null.
我认为 myString 不是字符串而是字符串数组。这是您需要做的:
I think that myString is not a string but an array of strings. Here is what you need to do:
您可以使用以下方法检查字符串是否等于 null:
如果结果为 0,则 (Test+"") = "null"。
You can check string equal to null using this:
If the result is 0 then (Test+"") = "null".
我在我正在构建的 Android 应用程序中尝试了上面给出的大多数示例,但都失败了。所以我想出了一个随时适合我的解决方案。
因此,只需像上面 l 那样连接一个空字符串并针对“null”进行测试,它就可以正常工作。事实上没有抛出异常
I tried most of the examples given above for a null in an android app l was building and IT ALL FAILED. So l came up with a solution that worked anytime for me.
So simply concatenate an empty string as l did above and test against "null" and it works fine. In fact no exception is thrown
例外也可能有帮助:
Exception may also help:
我正在使用这样的函数,将获取字符串结果传递给它,这样我就不必不断检查 null,它要么返回您传回的字符串,要么返回空(如果它为 null):
I'm using a function like this where I pass the get string result into it so I don't have to constantly check null and it either returns the string you passed back or empty if it's null:
您必须检查 null
if(str != null)。
You have to check with null
if(str != null).