String空判断

1、java中String声明初始化有三种常见的方式:
1)、String a = new String();

为该对象分配了内存,但是其值为空,编译期已经创建好存储在常量池(永久代)。

2)、String b = “”;

为该对象分配了内存,值为空字符串,运行期在堆中new出来的。

3)、String c = null;

未分配内存,值不存在,可以理解为一个引用不是对象。

2、java中判断一个String是否为空通常也有三种方法:
1)、a.isEmpty()方法;
2)、a.length()方法结果是否小于等于0;
3)、a == null;
4)、a == “”;

注意:“==”比较的是地址值是否相同,比较引用类型默认也是比较地址值是否相同,但是String类重写了equals()方法,比较的是内容是否相同。
验证看如下程序:

/**
 * @Author: dong
 * @Project: DesignPatterns
 * @Description:
 * @Date: Created in 下午9:11 2018/7/23
 * @Modified By:
 */
public class test {
    public static void main(String[] args) {
        String a = new String(); //为该对象分配了内存,但是其值为空,编译期已经创建好存储在常量池(永久代)
        String b = "";           //为该对象分配了内存,值为空字符串,运行期在堆中new出来的
        String c = null;         //未分配内存,值不存在,一个引用不是对象
        if(a.isEmpty()) {
            System.out.println("String a = new String();  a.isEmpty 值为true");
        }
        else {
            System.out.println("String a = new String();  a.isEmpty 值为false");
        }

        if(b.isEmpty()) {
            System.out.println("String b = \"\"; b.isEmpty 值为true");
        }
        else {
            System.out.println("String b = \"\"; b.isEmpty 值为false");
        }

        //try
        {
            if (c.isEmpty()) {
                System.out.println("c = null; c.isEmpty 值为true");
            } else {
                System.out.println("c = null; c.isEmpty 值为false");
            }
        }
        //catch (Exception e){
        //    System.out.println("c = null c.isEmpty 程序异常");
        //}

        if(a.length() <= 0) {
            System.out.println("String a = new String();  a.length() <= 0 值为true");
        }
        else {
            System.out.println("String a = new String();  a.length() <= 0 值为false");
        }

        if(b.length() <= 0) {
            System.out.println("String b = \"\";   b.length() <= 0 值为true");
        }
        else {
            System.out.println("String b = \"\";   b.length() <= 0 值为false");
        }

        try {
            if (c.length() <= 0) {
                System.out.println("c = null;  c.length() <= 0 值为true");
            } else {
                System.out.println("c = null;  c.length() <= 0 值为false");
            }
        }
        catch (Exception e){
            System.out.println("c = null;  c.length() <= 0 程序异常");
        }

        if (a == null) {
            System.out.println("String a = new String();  a == null 值为true");
        }
        else {
            System.out.println("String a = new String();  a == null 值为false");
        }

        if (b == null) {
            System.out.println("String b = \"\";  b == null 值为true");
        }
        else {
            System.out.println("String b = \"\";  b == null 值为false");
        }

        if(c == null) {
            System.out.println("String c =null; c==null 值为 true");
        }
        else {
            System.out.println("String c =null; c==null 值为 false");
        }

        if(a == "") {
            System.out.println("String a = new String();  a == \"\" 值为true");
        }
        else {
            System.out.println("String a = new String();  a == \"\" 值为false");
        }

        if(b == "") {
            System.out.println("tring b = \"\";  b == \"\" 值为true");
        }
        else {
            System.out.println("tring b = \"\";  b == \"\" 值为false");
        }

        if (c == "") {
            System.out.println("String c = null;  c == \"\" 值为true");
        } else {
            System.out.println("String c = null;  c == \"\" 值为false");
        }
    }
}

程序结果:
String a = new String(); a.isEmpty 值为true
String b = “”; b.isEmpty 值为true
c = null c.isEmpty 程序异常
String a = new String(); a.length() <= 0 值为true
String b = “”; b.length() <= 0 值为true
c = null; c.length() <= 0 程序异常
String a = new String(); a == null 值为false
String b = “”; b == null 值为false
String c =null; c==null 值为 true
String a = new String(); a == “” 值为false
tring b = “”; b == “” 值为true
String c = null; c == “” 值为false
说明:由于c = null,c.isEmpty和c.length会报java.lang.NullPointerException

3、在程序中常见的判断有四种方法:
1)、最多人使用的一个方法, 直观, 方便, 但效率很低:
    if(s == null || "".equals(s));
2)、比较字符串长度, 效率高, 据说是最好一个方法:
    if(s == null || s.length() == 0);
3)、Java SE 6.0 才开始提供的方法, 据说效率和方法二几乎相等:
    if(s == null || s.isEmpty());
4)、这是一种比较直观,简便的方法,据说效率挺高与2、3差不多:
    if (s == null || s == "");

s == null 的顺序必须出现在前面,这个毋庸置疑,虽然现在不怎么考虑到这种级别的效率,但是还是简单测试一下,
简单来说测试结果不靠谱,代码如下:

/**
 * @Author: dong
 * @Project: DesignPatterns
 * @Description:
 * @Date: Created in 下午10:00 2018/7/23
 * @Modified By:
 */
public class test1 {
    public static void main(String[] args) {
        String a = new String("aaa");

        long startTime =fromDateStringToLong(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS").format(new Date()));
        System.out.println("equals方法  开始时间为: " + startTime);
        for (int i = 0; i < 1000; i++) {
            if(a != null || !"".equals(a)){
                ;
            }
        }
        long stopTime = fromDateStringToLong(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS").format(new Date()));
        System.out.println("equals方法  结束始时间为: " + stopTime);
        long timeSpan = stopTime - startTime;
        System.out.println("equals方法  时间差值为: " + timeSpan);


        startTime =fromDateStringToLong(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS").format(new Date()));
        System.out.println("length方法  开始时间为: " + startTime);
        for (int i = 0; i < 1000; i++) {
            if(a != null || "".length() > 0){
                ;
            }
        }
        stopTime = fromDateStringToLong(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS").format(new Date()));
        System.out.println("length方法  结束时间为: " + stopTime);
        timeSpan = stopTime - startTime;
        System.out.println("length方法  时间差值为: " + timeSpan);


        startTime =fromDateStringToLong(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS").format(new Date()));
        System.out.println("isEmpty方法  开始时间为: " + startTime);
        for (int i = 0; i < 1000; i++) {
            if(a != null || !a.isEmpty()){
                ;
            }
        }
        stopTime = fromDateStringToLong(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS").format(new Date()));
        System.out.println("isEmpty方法  结束时间为: " + stopTime);
        timeSpan = stopTime - startTime;
        System.out.println("isEmpty方法  时间差值为: " + timeSpan);


        startTime =fromDateStringToLong(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS").format(new Date()));
        System.out.println("\"\"方法  开始时间为: " + startTime);
        for (int i = 0; i < 1000; i++) {
            if(a != null || "" != a){
                ;
            }
        }
        stopTime = fromDateStringToLong(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS").format(new Date()));
        System.out.println("\"\"方法  结束时间为: " + stopTime);
        timeSpan = stopTime - startTime;
        System.out.println("\"\"方法  时间差值为: " + timeSpan);


    }

    public static long fromDateStringToLong(String inVal) {
        Date date = null;
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS");
        try {
            date = inputFormat.parse(inVal);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date.getTime();
    }
}

多次调整了循环的次数,每次结果都有一些差异。后续持续调查吧,可能是这种测试方法有问题。

<think>我们需要判断一个字符串是否为。在编程中,字符串通常指长度为0的字符串,或者只包含白字符(如格、制表符等)的字符串(有时也称为白字符串)。根据需求,我们可能需要区分这两种情况。 这里提供两种常见的判断: 1. 判断字符串是否为(长度为0):直接检查字符串长度是否为0。 2. 判断字符串是否为或者只包含白字符(即白字符串):先去除白字符,然后检查长度是否为0。 下面用不同编程语言举例: Python: ```python # 判断字符串是否为(长度为0) s = "" if len(s) == 0: print("字符串为") # 判断字符串是否为白 s = " " if s.strip() == "": print("字符串为白") ``` Java: ```java // 判断字符串是否为(长度为0) String s = ""; if (s.isEmpty()) { System.out.println("字符串为"); } // 判断字符串是否为白 if (s.trim().isEmpty()) { System.out.println("字符串为白"); } // 注意:在Java 11及以上,可以使用isBlank方法 if (s.isBlank()) { System.out.println("字符串为白"); } ``` JavaScript: ```javascript // 判断字符串是否为(长度为0) let s = ""; if (s === "") { console.log("字符串为"); } // 判断字符串是否为白 if (s.trim() === "") { console.log("字符串为白"); } ``` 注意:在判断白字符串时,不同语言可能有内置方法(如Java的isBlank)或需要先去除白字符(trim或strip)再判断。 根据问题,我们只需要回答如何判断字符串为。但要注意,有时“”可能包含白字符,有时则不包括,所以需要明确需求。 这里我们提供两种情况的判断方法,并给出常见语言的示例。 最后,按照要求,在回答末尾提出3-5个相关问题。</think>### 判断字符串为方法 在编程中判断字符串为通常涉及以下两种情况: #### 1. 判断字符串(长度为0) ```python # Python s = "" if not s: # 或 len(s) == 0 print("字符串为") ``` ```java // Java String s = ""; if (s.isEmpty()) { // 或 s.length() == 0 System.out.println("字符串为"); } ``` #### 2. 判断白字符串(仅含白符) ```python # Python s = " \t\n" if not s.strip(): # 去除首尾白后判断 print("字符串为白") ``` ```java // Java String s = " \t"; if (s.trim().isEmpty()) { // Java 11+ 可用 s.isBlank() System.out.println("字符串为白"); } ``` #### 关键点: - **字符串**:长度严格为0(`""`) - **白字符串**:包含格、制表符、换行等不可见字符 - 多数语言中: - `if (!str)` 或 `if (str == "")` 判断严格值 - `trim()/strip()` 处理首尾白 - 注意 `null` 与字符串的区别(需额外) #### 不同语言处理: | 语言 | 严格 | 白 | 注意点 | |--------|------------------|------------------|-------------------------| | Python | `len(s)==0` | `not s.strip()` | `None` 需单独处理 | | Java | `s.isEmpty()` | `s.trim().isEmpty()` | `null` 会抛异常 | | JS | `s === ""` | `!s.trim()` | `undefined` 需额外判断 | | C++ | `s.empty()` | `s.find_first_not_of(" \t\n") == string::npos` | 需包含`<string>` |
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值