记用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 异常。

原文地址:https://www.cnblogs.com/famine/p/9389431.html