将字符串拆分为填充null的数组

时间:2014-08-14 09:07:27

标签: java arrays split

我正在尝试循环,我将String拆分为String []

sumc是一个arraylist,它是一个全局变量 cind和dbind是String []以及全局变量

 for (int i = 0 ; i <= sumc.length - 1 ; i++){

        String local = sumc[i];

        System.out.println(local);

        String[] parts = local.split(":");
        System.out.println(parts[0]);
        System.out.println(parts[1]);
        cind = new String [sumc.length];
        dbind = new String [sumc.length];
        cind[i] = local.split(":")[0];
        dbind[i] = local.split(":")[1];

    }

    System.out.println(Arrays.toString(cind) + "\t");
    System.out.println(Arrays.toString(dbind) + "\t");

因此,当我执行此打印时,我只得到null,null,null除了最后一个,其中填充了数字

1 个答案:

答案 0 :(得分:3)

您正在循环中实例化cinddbind 。这应该解决它:

cind = new String [sumc.length];
dbind = new String [sumc.length]; 
for (int i = 0 ; i <= sumc.length - 1 ; i++){

    String local = sumc[i];

    System.out.println(local);

    String[] parts = local.split(":");
    System.out.println(parts[0]);
    System.out.println(parts[1]);
    cind[i] = local.split(":")[0];
    dbind[i] = local.split(":")[1];

}

System.out.println(Arrays.toString(cind) + "\t");
System.out.println(Arrays.toString(dbind) + "\t");

数组 sumc转换为类似表格的结构的更简洁方法如下:

String[][] data = new String[sumc.length][2];
for (int i = 0; i < sumc.length; i++)
    data[i] = sumc[i].split(":");

分别通过data[i][0]data[i][1]进行访问。