Java split split string to avoid pits

There are 2 points to note when using split for string segmentation

1. When special characters are used as separators, you need to use \\ to escape (such as \\ -> \\\\; | -> \\|)

Special characters

.$|()[{^?*+\\

For example, "|" separated

Unescaped

        String str = "01|02|03"; 
        String[] strArr = str.split("|");
        System.out.println(strArr.length); //输出8
        for (int i = 0; i < strArr.length; ++i) {
            System.out.println(strArr[i]);//输出0 1 | 0 2 | 0 3 
        }

Escape

        String str = "01|02|03"; 
        String[] strArr = str.split("\\|");
        System.out.println(strArr.length); //输出3
        for (int i = 0; i < strArr.length; ++i) {
            System.out.println(strArr[i]);//输出01 02 03
        }

or

        String str = "01|02|03"; 
        String[] strArr = str.split("[|]");
        System.out.println(strArr.length); //输出3
        for (int i = 0; i < strArr.length; ++i) {
            System.out.println(strArr[i]);//输出01 02 03
        }

or

        String str = "01|02|03";
        // 以|为分隔符来分隔字符串
        StringTokenizer st=new StringTokenizer(str,"|");
        while(st.hasMoreTokens()) {
        	System.out.println(st.nextToken());//输出01 02 03
        }

2. Pay attention to the processing of the last empty character (usually in some cases when the final data is empty, only a separator is reserved. If it is not processed, the number of data after splitting is not the same as expected)

        String str = "01|02|03|"; //注意在最后多了一个|分隔符
        String[] strArr = str.split("\\|");
        System.out.println(strArr.length); //输出3
        for (int i = 0; i < strArr.length; ++i) {
            System.out.println(strArr[i]);//输出01 02 03
        }

If you need to keep the data of the last null character, you need to set the second parameter of split to -1

        String str = "01|02|03|"; //注意在最后多了一个|分隔符
        String[] strArr = str.split("\\|",-1);
        System.out.println(strArr.length); //输出4
        for (int i = 0; i < strArr.length; ++i) {
            System.out.println(strArr[i]);//输出01 02 03 空字符
        }

Split source screenshot 

Guess you like

Origin blog.csdn.net/lw112190/article/details/107022115