如何检查我的字符串是否等于 null?

发布于 2024-08-28 07:56:17 字数 760 浏览 8 评论 0 原文

仅当我的字符串具有有意义的值时,我才想执行某些操作。所以,我尝试了这个。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(28

往事随风而去 2024-09-04 07:56:17
if (myString != null && !myString.isEmpty()) {
  // doSomething
}

作为进一步的评论,您应该了解 equals 合约中的这个术语:

来自 Object.equals(Object)

对于任何非空引用值xx.equals(null)返回 false

null比较的方法是使用x == nullx != null

此外,如果x == nullx.fieldx.method()会抛出NullPointerException

if (myString != null && !myString.isEmpty()) {
  // doSomething
}

As further comment, you should be aware of this term in the equals contract:

From Object.equals(Object):

For any non-null reference value x, x.equals(null) should return false.

The way to compare with null is to use x == null and x != null.

Moreover, x.field and x.method() throws NullPointerException if x == null.

花心好男孩 2024-09-04 07:56:17

如果 myStringnull,则调用 myString.equals(null)myString.equals("") 将失败并出现 NullPointerException。您不能对 null 变量调用任何实例方法。

首先检查 null ,如下所示:

if (myString != null && !myString.equals("")) {
    //do something
}

这利用 短路评估 来不尝试如果 myString 未通过 null 检查,则 .equals

If myString is null, then calling myString.equals(null) or myString.equals("") will fail with a NullPointerException. You cannot call any instance methods on a null variable.

Check for null first like this:

if (myString != null && !myString.equals("")) {
    //do something
}

This makes use of short-circuit evaluation to not attempt the .equals if myString fails the null check.

她说她爱他 2024-09-04 07:56:17

Apache commons StringUtils.isNotEmpty 是最好的方法。

Apache commons StringUtils.isNotEmpty is the best way to go.

剧终人散尽 2024-09-04 07:56:17

如果 myString 实际上为 null,则对该引用的任何调用都将失败并出现空指针异常 (NPE)。
从 java 6 开始,使用 #isEmpty 而不是长度检查(在任何情况下都不要使用检查创建新的空字符串)。

if (myString != null &&  !myString.isEmpty()){
    doSomething();
}

顺便说一句,如果像您一样与字符串文字进行比较,则会反转该语句,以便不必进行空检查,即

if ("some string to check".equals(myString)){
  doSomething();
} 

代替:

if (myString != null &&  myString.equals("some string to check")){
    doSomething();
}

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).

if (myString != null &&  !myString.isEmpty()){
    doSomething();
}

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,

if ("some string to check".equals(myString)){
  doSomething();
} 

instead of :

if (myString != null &&  myString.equals("some string to check")){
    doSomething();
}
别在捏我脸啦 2024-09-04 07:56:17

正在运行!!!

 if (myString != null && !myString.isEmpty()) {
        return true;
    }
    else {
        return false;
    }

已更新

对于 Kotlin,我们通过以下方式检查字符串是否为空

return myString.isNullOrEmpty() // Returns `true` if this nullable String is either `null` or empty, false otherwise

return myString.isEmpty() // Returns `true` if this char sequence is empty (contains no characters), false otherwise

WORKING !!!!

 if (myString != null && !myString.isEmpty()) {
        return true;
    }
    else {
        return false;
    }

Updated

For Kotlin we check if the string is null or not by following

return myString.isNullOrEmpty() // Returns `true` if this nullable String is either `null` or empty, false otherwise

return myString.isEmpty() // Returns `true` if this char sequence is empty (contains no characters), false otherwise
蒗幽 2024-09-04 07:56:17

您需要检查 myString 对象是否为 null

if (myString != null) {
    doSomething
}

You need to check that the myString object is null:

if (myString != null) {
    doSomething
}
韬韬不绝 2024-09-04 07:56:17

如果您的字符串为空,这样的调用应该抛出 NullReferenceException:

myString.equals(null)

但无论如何,我认为这样的方法就是您想要的:

public static class StringUtils
{
    public static bool isNullOrEmpty(String myString)
    {
         return myString == null || "".equals(myString);
    }
}

然后在您的代码中,您可以执行以下操作:

if (!StringUtils.isNullOrEmpty(myString))
{
    doSomething();
}

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:

public static class StringUtils
{
    public static bool isNullOrEmpty(String myString)
    {
         return myString == null || "".equals(myString);
    }
}

Then in your code, you can do things like this:

if (!StringUtils.isNullOrEmpty(myString))
{
    doSomething();
}
不知在何时 2024-09-04 07:56:17

我鼓励使用现有的实用程序,或创建您自己的方法:

public static boolean isEmpty(String string) {
    return string == null || string.length() == 0;
}

然后在需要时使用它:

if (! StringUtils.isEmpty(string)) {
  // do something
}

如上所述,||和&&操作者短路。这意味着一旦他们能够确定自己的价值,他们就会停止。因此,如果 (string == null) 为 true,则不需要计算长度部分,因为表达式始终为 true。与 && 类似,如果左侧为 false,则表达式始终为 false,无需进一步求值。

作为补充说明,使用长度通常比使用 .equals 更好。性能稍好一些(不多),并且不需要创建对象(尽管大多数编译器可能会对此进行优化)。

I would encourage using an existing utility, or creating your own method:

public static boolean isEmpty(String string) {
    return string == null || string.length() == 0;
}

Then just use it when you need it:

if (! StringUtils.isEmpty(string)) {
  // do something
}

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).

在梵高的星空下 2024-09-04 07:56:17

尝试,

myString!=null && myString.length()>0

Try,

myString!=null && myString.length()>0
£噩梦荏苒 2024-09-04 07:56:17
 if (myString != null && myString.length() > 0) {

        // your magic here

 }

顺便说一句,如果您要进行大量字符串操作,那么有一个很棒的 Spring 类,其中包含各种有用的方法:

http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/util/StringUtils.html

 if (myString != null && myString.length() > 0) {

        // your magic here

 }

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

本宫微胖 2024-09-04 07:56:17

每次我必须处理字符串(几乎每次)时,我都会停下来想知道哪种方法才是检查空字符串的最快方法。当然, 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。结果如下:

String.IsNullOrEmpty()
NULL = 62 milliseconds
Empty = 46 milliseconds
"" = 46 milliseconds

str == null
NULL = 31 milliseconds
Empty = 46 milliseconds
"" = 31 milliseconds

str == null || str == String.Empty
NULL = 46 milliseconds
Empty = 62 milliseconds
"" = 359 milliseconds

str == null || str == ""
NULL = 46 milliseconds
Empty = 343 milliseconds
"" = 78 milliseconds

str == null || str.length == 0
NULL = 31 milliseconds
Empty = 63 milliseconds
"" = 62 milliseconds

根据这些结果,平均检查 str == null 是最快的,但可能并不总是能得到我们想要的结果。 如果 str = String.Emptystr = "",则结果为 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:

String.IsNullOrEmpty()
NULL = 62 milliseconds
Empty = 46 milliseconds
"" = 46 milliseconds

str == null
NULL = 31 milliseconds
Empty = 46 milliseconds
"" = 31 milliseconds

str == null || str == String.Empty
NULL = 46 milliseconds
Empty = 62 milliseconds
"" = 359 milliseconds

str == null || str == ""
NULL = 46 milliseconds
Empty = 343 milliseconds
"" = 78 milliseconds

str == null || str.length == 0
NULL = 31 milliseconds
Empty = 63 milliseconds
"" = 62 milliseconds

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 or str = "", it results in false. Then you have 2 that are tied in second place: String.IsNullOrEmpty() and str == null || str.length == 0. Since String.IsNullOrEmpty() looks nicer and is easier (and faster) to write I would recommend using it over the other solution.

仙女 2024-09-04 07:56:17

我会做这样的事情:

( myString != null && myString.length() > 0 )
    ? doSomething() : System.out.println("Non valid String");
  • 测试 null 检查 myString 是否包含 String 的实例。
  • length() 返回长度,相当于 equals("")。
  • 首先检查 myString 是否为 null 将避免 NullPointerException。

I'd do something like this:

( myString != null && myString.length() > 0 )
    ? doSomething() : System.out.println("Non valid String");
  • Testing for null checks whether myString contains an instance of String.
  • length() returns the length and is equivalent to equals("").
  • Checking if myString is null first will avoid a NullPointerException.
猫瑾少女 2024-09-04 07:56:17

我一直在使用 StringUtil.isBlank(string)

它测试字符串是否为空: null、emtpy 或只有空格。

所以这是迄今为止最好的,

这是文档中的原始方法

/**
    * Tests if a string is blank: null, emtpy, or only whitespace (" ", \r\n, \t, etc)
    * @param string string to test
    * @return if string is blank
    */
    public static boolean isBlank(String string) {
        if (string == null || string.length() == 0)
            return true;

        int l = string.length();
        for (int i = 0; i < l; i++) {
            if (!StringUtil.isWhitespace(string.codePointAt(i)))
                return false;
        }
        return true;
    } 

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

/**
    * Tests if a string is blank: null, emtpy, or only whitespace (" ", \r\n, \t, etc)
    * @param string string to test
    * @return if string is blank
    */
    public static boolean isBlank(String string) {
        if (string == null || string.length() == 0)
            return true;

        int l = string.length();
        for (int i = 0; i < l; i++) {
            if (!StringUtil.isWhitespace(string.codePointAt(i)))
                return false;
        }
        return true;
    } 
牛↙奶布丁 2024-09-04 07:56:17

对我来说,在 Java 中检查字符串是否具有任何有意义的内容的最佳方法是:

string != null && !string.trim().isEmpty()

首先检查字符串是否为 null 以避免 NullPointerException,然后修剪所有空格字符以避免检查只有空格的字符串,最后检查修剪后的字符串是否不为空,即长度是否为 0。

For me the best check if a string has any meaningful content in Java is this one:

string != null && !string.trim().isEmpty()

First you check if the string is null to avoid NullPointerException 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.

一曲爱恨情仇 2024-09-04 07:56:17

这应该有效:

if (myString != null && !myString.equals(""))
    doSomething
}

如果没有,那么 myString 可能有一个您不期望的值。尝试像这样打印出来:

System.out.println("+" + myString + "+");

使用“+”符号包围字符串将显示其中是否存在您没有考虑到的额外空格。

This should work:

if (myString != null && !myString.equals(""))
    doSomething
}

If not, then myString likely has a value that you are not expecting. Try printing it out like this:

System.out.println("+" + myString + "+");

Using the '+' symbols to surround the string will show you if there is extra whitespace in there that you're not accounting for.

月光色 2024-09-04 07:56:17

if(str.isEmpty() || str==null){
做你想做的事
}

if(str.isEmpty() || str==null){
do whatever you want
}

成熟稳重的好男人 2024-09-04 07:56:17

好吧,这就是 Java 中数据类型的工作原理。 (请原谅我的英语,我可能没有使用正确的词汇。
你必须区分其中两个。基本数据类型和普通数据类型。基本数据类型几乎构成了现有的一切。
例如,有所有数字、字符、布尔值等。
普通数据类型或复杂数据类型就是其他一切。
字符串是一个字符数组,因此是一种复杂的数据类型。

您创建的每个变量实际上都是内存中值的指针。
例如:

String s = new String("This is just a test");

变量“s”不包含字符串。它是一个指针。该指针指向内存中的变量。
当您调用 System.out.println(anyObject) 时,将调用该对象的 toString() 方法。如果它没有从 Object 覆盖 toString,它将打印指针。
例如:

public class Foo{
    public static void main(String[] args) {
        Foo f = new Foo();
        System.out.println(f);
    }
}

>>>>
>>>>
>>>>Foo@330bedb4

“@”后面的所有内容都是指针。这只适用于复杂的数据类型。原始数据类型直接保存在它们的指针中。所以实际上没有指针,而是直接存储值。

例如:

int i = 123;

在这种情况下 i 不存储指针。我将存储整数值 123(以字节 ofc 为单位)。

好的,让我们回到 == 运算符。
它总是比较指针,而不是比较内存中指针位置处保存的内容。

示例:

String s1 = new String("Hallo");
String s2 = new String("Hallo");

System.out.println(s1 == s2);

>>>>> false

这两个字符串都有不同的指针。然而 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:

String s = new String("This is just a test");

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), the toString() method of that object is called. If it did not override toString from Object, it will print the pointer.
For example:

public class Foo{
    public static void main(String[] args) {
        Foo f = new Foo();
        System.out.println(f);
    }
}

>>>>
>>>>
>>>>Foo@330bedb4

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:

int i = 123;

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:

String s1 = new String("Hallo");
String s2 = new String("Hallo");

System.out.println(s1 == s2);

>>>>> false

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

小苏打饼 2024-09-04 07:56:17

我在android中遇到了这个问题,我使用这种方式(为我工作):

String test = null;
if(test == "null"){
// Do work
}

但是在java代码中我使用:

String test = null;
if(test == null){
// Do work
}

并且:

private Integer compareDateStrings(BeanToDoTask arg0, BeanToDoTask arg1, String strProperty) {
    String strDate0 = BeanUtils.getProperty(arg0, strProperty);_logger.debug("strDate0 = " + strDate0);
    String strDate1 = BeanUtils.getProperty(arg1, strProperty);_logger.debug("strDate1 = " + strDate1);
    return compareDateStrings(strDate0, strDate1);
}

private Integer compareDateStrings(String strDate0, String strDate1) {
    int cmp = 0;
    if (isEmpty(strDate0)) {
        if (isNotEmpty(strDate1)) {
            cmp = -1;
        } else {
            cmp = 0;
        }
    } else if (isEmpty(strDate1)) {
        cmp = 1;
    } else {
        cmp = strDate0.compareTo(strDate1);
    }
    return cmp;
}

private boolean isEmpty(String str) {
    return str == null || str.isEmpty();
}
private boolean isNotEmpty(String str) {
    return !isEmpty(str);
}

I had this problem in android and i use this way (Work for me):

String test = null;
if(test == "null"){
// Do work
}

But in java code I use :

String test = null;
if(test == null){
// Do work
}

And :

private Integer compareDateStrings(BeanToDoTask arg0, BeanToDoTask arg1, String strProperty) {
    String strDate0 = BeanUtils.getProperty(arg0, strProperty);_logger.debug("strDate0 = " + strDate0);
    String strDate1 = BeanUtils.getProperty(arg1, strProperty);_logger.debug("strDate1 = " + strDate1);
    return compareDateStrings(strDate0, strDate1);
}

private Integer compareDateStrings(String strDate0, String strDate1) {
    int cmp = 0;
    if (isEmpty(strDate0)) {
        if (isNotEmpty(strDate1)) {
            cmp = -1;
        } else {
            cmp = 0;
        }
    } else if (isEmpty(strDate1)) {
        cmp = 1;
    } else {
        cmp = strDate0.compareTo(strDate1);
    }
    return cmp;
}

private boolean isEmpty(String str) {
    return str == null || str.isEmpty();
}
private boolean isNotEmpty(String str) {
    return !isEmpty(str);
}
海风掠过北极光 2024-09-04 07:56:17

我更喜欢使用:

if(!StringUtils.isBlank(myString)) { // checks if myString is whitespace, empty, or null
    // do something
}

阅读StringUtils.isBlank() vs String.isEmpty()

I prefer to use:

if(!StringUtils.isBlank(myString)) { // checks if myString is whitespace, empty, or null
    // do something
}

Read StringUtils.isBlank() vs String.isEmpty().

无力看清 2024-09-04 07:56:17

在 Android 中,您可以使用 TextUtils 中的实用程序方法 isEmpty 进行检查,

public static boolean isEmpty(CharSequence str) {
    return str == null || str.length() == 0;
}

isEmpty(CharSequence str) 方法检查两个条件,对于 null< /code> 和长度。

In Android you can check this with utility method isEmpty from TextUtils,

public static boolean isEmpty(CharSequence str) {
    return str == null || str.length() == 0;
}

isEmpty(CharSequence str) method check both condition, for null and length.

林空鹿饮溪 2024-09-04 07:56:17

如果您在 Android 中工作,那么您可以使用简单的 TextUtils 类。
检查以下代码:

if(!TextUtils.isEmpty(myString)){
 //do something
}

这是代码的简单用法。答案可能会重复。但为您提供单一且简单的检查很简单。

If you are working in Android then you can use the simple TextUtils class.
Check the following code:

if(!TextUtils.isEmpty(myString)){
 //do something
}

This is simple usage of code. Answer may be repeated. But is simple to have single and simple check for you.

云裳 2024-09-04 07:56:17

我总是这样使用:

if (mystr != null && !mystr.isEmpty()){
  //DO WHATEVER YOU WANT OR LEAVE IT EMPTY
}else {
  //DO WHATEVER YOU WANT OR LEAVE IT EMPTY
}

或者您可以将其复制到您的项目中:

private boolean isEmptyOrNull(String mystr){
    if (mystr != null && !mystr.isEmpty()){ return true; }
    else { return false; }
}

然后像这样调用它:

boolean b = isEmptyOrNull(yourString);

如果为空或 null 它将返回 true。
b=true 如果为空或 null

或当它为空时,你可以使用try catch和catch。

I always use like this:

if (mystr != null && !mystr.isEmpty()){
  //DO WHATEVER YOU WANT OR LEAVE IT EMPTY
}else {
  //DO WHATEVER YOU WANT OR LEAVE IT EMPTY
}

or you can copy this to your project:

private boolean isEmptyOrNull(String mystr){
    if (mystr != null && !mystr.isEmpty()){ return true; }
    else { return false; }
}

and just call it like :

boolean b = isEmptyOrNull(yourString);

it will return true if is empty or null.
b=true if is empty or null

or you can use try catch and catch when it is null.

超可爱的懒熊 2024-09-04 07:56:17

我认为 myString 不是字符串而是字符串数组。这是您需要做的:

String myNewString = join(myString, "")
if (!myNewString.equals(""))
{
    //Do something
}

I think that myString is not a string but an array of strings. Here is what you need to do:

String myNewString = join(myString, "")
if (!myNewString.equals(""))
{
    //Do something
}
像你 2024-09-04 07:56:17

您可以使用以下方法检查字符串是否等于 null:

String Test = null;
(Test+"").compareTo("null")

如果结果为 0,则 (Test+"") = "null"。

You can check string equal to null using this:

String Test = null;
(Test+"").compareTo("null")

If the result is 0 then (Test+"") = "null".

醉态萌生 2024-09-04 07:56:17

我在我正在构建的 Android 应用程序中尝试了上面给出的大多数示例,但都失败了。所以我想出了一个随时适合我的解决方案。

String test = null+"";
If(!test.equals("null"){
       //go ahead string is not null

}

因此,只需像上面 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.

String test = null+"";
If(!test.equals("null"){
       //go ahead string is not null

}

So simply concatenate an empty string as l did above and test against "null" and it works fine. In fact no exception is thrown

挥剑断情 2024-09-04 07:56:17

例外也可能有帮助:

try {
   //define your myString
}
catch (Exception e) {
   //in that case, you may affect "" to myString
   myString="";
}

Exception may also help:

try {
   //define your myString
}
catch (Exception e) {
   //in that case, you may affect "" to myString
   myString="";
}
沐歌 2024-09-04 07:56:17

我正在使用这样的函数,将获取字符串结果传递给它,这样我就不必不断检查 null,它要么返回您传回的字符串,要么返回空(如果它为 null):

public static String safeGet(String str) {
    try {
        if (str == null) throw new Exception();
        return "" + str;
    } catch (Exception e) {
        return "";
    }
}

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:

public static String safeGet(String str) {
    try {
        if (str == null) throw new Exception();
        return "" + str;
    } catch (Exception e) {
        return "";
    }
}
夏日浅笑〃 2024-09-04 07:56:17

您必须检查 null if(str != null)。

You have to check with null if(str != null).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文