日期:2014-05-20  浏览次数:21004 次

如何去掉String数组中的空值,形成新的String数组
比如,String[] aa = {"","","ddd","","asdf" }
我只想保留"ddd"和"asdf",该怎么作?

------解决方案--------------------
Java code

String[] aa = {"","","ddd","","asdf" };
        List<String> tmp = new ArrayList<String>();
        for(String str:aa){
            if(str!=null && str.length()!=0){
                tmp.add(str);
            }
        }
        aa = tmp.toArray(new String[0]);

------解决方案--------------------
Java code


public class Arr {
    public static void main(String[] args) {
        String[] aa = {"","","ddd","","asdf"};
        
        //用StringBuffer来存放数组中的非空元素,用“;”分隔
        StringBuffer sb = new StringBuffer();
        for(int i=0; i<aa.length; i++) {
            if("".equals(aa[i])) {
                continue;
            }
            sb.append(aa[i]);
            if(i != aa.length - 1) {
                sb.append(";");
            }
        }
        //用String的split方法分割,得到数组
        aa = sb.toString().split(";");
        
        //打印数组
        for(int i=0; i<aa.length; i++) {
            System.out.print(aa[i] + " ");
        }
        System.out.println();
    }
}