判断字符串是否为空,是否只有空格

来源:互联网 发布:淘宝联盟5.2苹果版本 编辑:程序博客网 时间:2024/06/05 03:17
方式一:自己判断
str != null && str.length() != 0

alternatively

str != null && !str.equals("")

or

str != null && !"".equals(str)

Note: The second check (first and second alternatives) assumes str is not null. It's ok only because the first check is doing that (and Java doesn't does the second check if the first is false)!

IMPORTANT: DON'T use == for string equality. == checks the pointer is equal, not the value. Two strings can be in different memory addresses (two instances) but have the same value!

2 引入外部类

Almost every library I know defines a utility class called StringUtilsStringUtil or StringHelper, and they usually include the method you are looking for.

My personal favorite is Apache Commons / Lang, where in the StringUtils class, you get both the

  1. StringUtils.isEmpty(String) and the
  2. StringUtils.isBlank(String) method

(The first checks whether a string is null or empty, the second checks whether it is null, empty or whitespace only)

3 Android中判断

Just adding Android in here:

import android.text.TextUtils;if (!TextUtils.isEmpty(str)) {...}

0 0
原创粉丝点击