记用split通过";"切割字符串,存入数组出现的小问题

通过一个java项目展示问题所在,以下是code:

package test;
import java.util.Arrays;

public class splitAndArr {
    String s;
    String[] arr;
    public splitAndArr(){}
    public splitAndArr(String s){
        this.arr=new String[s.length()];
        this.s=s;
    }

    public void print(String s){
        this.arr=s.split(";");  //这句是主角
        System.out.println("打印字符串:"+s);
        System.out.println("打印数组:"+Arrays.toString(this.arr));
        System.out.println("数组长度:"+this.arr.length);
        for(int i=0;i<this.arr.length;i++){
            System.out.println("a["+i+"]: "+this.arr[i]);
            if(this.arr[i].equals(""))System.out.println("出现空值");
        }
        System.out.println("----------------------------分割线");
    }

    public static void main(String[] args) {

        splitAndArr obj=new splitAndArr(";helloworld");
        splitAndArr obj2=new splitAndArr("hello;world");
        splitAndArr obj3=new splitAndArr("hello;;world");
        splitAndArr obj4=new splitAndArr("helloworld;;");
        //打印
        obj.print(obj.s);
        obj2.print(obj2.s);
        obj3.print(obj3.s);
        obj4.print(obj4.s);
    }

}

输出为:

打印字符串:;helloworld
打印数组:[, helloworld]
数组长度:2
a[0]: 
出现空值
a[1]: helloworld
----------------------------分割线
打印字符串:hello;world
打印数组:[hello, world]
数组长度:2
a[0]: hello
a[1]: world
----------------------------分割线
打印字符串:hello;;world
打印数组:[hello, , world]
数组长度:3
a[0]: hello
a[1]: 
出现空值
a[2]: world
----------------------------分割线
打印字符串:helloworld;;
打印数组:[helloworld]
数组长度:1
a[0]: helloworld
----------------------------分割线

仔细看最后一个:
分号切割后存入数组,将导致出现空值(equals可以判断到),更严重的是,如果分号出现在字符串末尾将导致数组没有存入空值!!

这时候,如果你以分号切割字符串,存入到数组中时将不能完全按照分号的个数来确定数组的大小,不然有可能造成 ArrayIndexOutOfBoundsException 异常。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

人生莫如饥荒

如果对您有帮助,也可以给点赏钱

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值