有人可以告诉我为什么此代码在array [0] [4]处有孔吗?

public class Random{

    public static void main (String []args){

        String [][] array={{"This is a test. A hole here"}};

        for(int i=0;i<array.length;i++){
            String temp=array[i][0];

            array[i]=temp.split("[\\:., ]");
        }

        System.out.print(array[0][4]);
    }
}


但是,当我在定界符(“ [\:。,] +”)上添加加号时,我得到了正确的输出。

public class Random{

    public static void main (String []args){

        String [][] array={{"This is a test. A hole here"}};

        for(int i=0;i<array.length;i++){
            String temp=array[i][0];
            array[i]=temp.split("[\\:., ]+");
        }

        System.out.print(array[0][4]);
    }
}


加号是否有消除此孔并解决此问题的原因?我愿意接受任何建议或意见。是的,我是新手。

最佳答案

使用array[i]=temp.split("[\\:., ]");,您的字符串将在此处拆分:

This is a test. A hole here
    ^  ^ ^    ^^ ^    ^


因此,您在array[4]处得到一个空字符串。

使用array[i]=temp.split("[\\:., ]+");会将“。”组合为一个“分割点”,因此不会在其中分割。

10-04 14:57
查看更多