str.split(",")和str.split(",",-1)的区别

public class SplitTest {


    public static void main(String[] args) {

        /**
         *  1.如果字符串最后一位有值,则没有区别,
         *  2.如果最后n位都是切割符,split(" ")不会继续切分,split(" ", -1)会继续切分
         */
        String str = "1,2,3,4,5, , , , ,10,,,,";

        String[] strArray = str.split(",");

        System.out.println("str1.split(\",\", -1):str1字符串长度为:" + str.length());

        printInfo(strArray);

        String[] strArray2 = str.split(",", -1);

        System.out.println();
        System.out.println("str1.split(\",\", -1):str1字符串长度为:" + str.length());

        printInfo(strArray2);
    }

    private static void printInfo(String[] strArray) {
        for (int i = 0; i < strArray.length; i++) {
            if (!strArray[i].matches("[0-9]*")) {
                System.out.println("格式不规范,请用逗号分隔");
                continue;
            }
            System.out.println("i=" + i + " " + strArray[i] + " ");
        }
    }
}

输出结果如下图所示:

str.split(

你可能感兴趣的:(java)