zoukankan      html  css  js  c++  java
  • 记用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 异常。

  • 相关阅读:
    asp.net 框架接触(2)
    解决:C++ 中 main函数 wmain函数 _tmain函数 WinMain函数 wWInMain函数 _tWinMain函数的区别
    实现:创建/复制/移动文件API
    实现:类模板的数组类封装
    python3 解析shodan_json数据
    实现:API实现创建用户并且添加至管理员
    学习:类模板
    网展cms后台任意文件删除和sql注入
    选择排序
    实现:函数模板实现不同数据类型数组进行排序
  • 原文地址:https://www.cnblogs.com/famine/p/9389431.html
Copyright © 2011-2022 走看看