如何检查字符串不为空?
if(string.equals("")) { }
如何检查字符串是否为空?
if(!string.equals("")) { }
通过if (string != null)
检查if (string != null)
如果你想检查它是null还是空 – 你需要if (string != null && !string.isEmpty())
我更喜欢使用commons-lang StringUtils.isNotEmpty(..)
您可以使用以下代码执行此操作:
if (string != null) { }
检查null是通过以下方式完成的:
string != null
您的示例实际上是检查空字符串
你可以把这两个结合起来:
if (string != null && !string.equals("")) { ...
但是null和empty是两个不同的东西
没有什么新的东西可以添加到上面的答案中,只需将其包装成一个简单的类。 Commons-lang是完全可以的,但如果您只需要这些或者更多的辅助函数,那么滚动您自己的简单类是最简单的方法,同时保持可执行文件的大小。
public class StringUtils { public static boolean isEmpty(String s) { return (s == null || s.isEmpty()); } public static boolean isNotEmpty(String s) { return !isEmpty(s); } }
使用TextUtils方法。
TextUtils.isEmpty(str) :如果字符串为null或0-length,则返回true。 参数:str要检查的字符串返回:如果str为null或零长度,则返回true
if(TextUtils.isEmpty(str)){ // str is null or lenght is 0 }
TextUtils类的来源
isEmpty方法:
public static boolean isEmpty(CharSequence str) { if (str == null || str.length() == 0) return true; else return false; }
if(str != null && !str.isEmpty())
请确保以此顺序使用&&的部分,因为如果&&的第一部分失败,java将不会继续评估第二部分,因此如果str为null,则确保不会从str.isEmpty()获得空指针exception。
请注意,它仅在Java SE 1.6之后可用。
您必须在先前版本上检查str.length() == 0 or str.equals("")
。
正如大家所说,你必须在你正在测试内存指针的对象中检查(string!= null)。
因为每个对象都由一个内存指针标识,所以在测试其他任何东西之前,你必须检查你的对象是否有空指针,所以:
(string!= null &&!string.equals(“”))很好
(!string.equals(“”)&& string!= null)可以给你一个nullpointerexception。
如果你不关心尾随空格你总是可以在equals()之前使用trim(),所以“”和“”会给你相同的结果
检查String的最佳方法是:
import org.apache.commons.lang3.StringUtils; if(StringUtils.isNotBlank(string)){ .... }
从文档 :
isBlank(CharSequence cs):
检查CharSequence是否为空(“”),仅为null或空格。
if(string != null)
要么
if(string.length() == 0)
要么
if(("").equals(string))
你可以试试这个
if(string != null)