The difference between subString and split

         Recently, when I was writing a project, it involved string cutting. When I started using it, I didn’t pay much attention to it. But when I used split to cut the dot, I found that I couldn’t cut it. What I got was an empty array (split wants To cut a point, you need to add an escape character), so I specifically inquired about the relevant information, and here is just a simple record.

The difference between subString and split:

SubString returns a string after cutting, and split returns a string array after cutting.

And the parameters passed by the two are still different. In the parameters of sbstring, you can pass various symbols without escaping, but in the parameters of split, some special symbols need to be escaped, otherwise you will get an empty array. .

Look directly at the demo case:

package demo1;

import java.util.Arrays;

public class SubStringOrSplitTest {
    public static void main(String[] args) {

        String fileName = "test.png";

        String[] split1 = fileName.split("."); //获取到的数组是空,而且idea也是会提醒的  调用“split()”时可疑的正则表达式“.”
        for (String s : split1) {
            System.out.println(s);
        }
        System.out.println("------------------");

        String[] split2 = fileName.split(",");
        for (String s : split2) {
            System.out.println(s);//获取到的test.png
        }

        System.out.println("------------------");

        String[] split3 = fileName.split("\\.");  //使用转义符号就可以使用点进行切割了
        for (String s : split3) {
            System.out.println(s);
        }  //输出结果  test  png

        //如果用“|”作为分隔的话,必须是如下写法:使用split对字符串进行切割会出现很多意向不到的结果,所以使用的时候一定要自己写案例测试成功后再写到项目中
        //String.split("\\|"),这样才能正确的分隔开,不能用String.split("|");

        System.out.println("------------------");

        String fileName2 = "test1.txt,test2.txt,test3.txt";
        String[] split4 = fileName2.split(",");  //这个就可以切割出来 因为,不用进行转义
        for (String s : split4) {
            System.out.println(s); // 输出 test1.txt   test2.txt   test3.txt"
        }

        System.out.println("------------------");
        String[] split5 = fileName2.split(",", 2);  //会以,为分割好,把字符串切割成两份
        for (String s : split5) {
            System.out.println(s); // 输出test1.txt    test2.txt,test3.txt"
        }

        System.out.println("------------------");
        String substring = fileName.substring(fileName.lastIndexOf("."));
        System.out.println(substring); //输出.png

        String substring1 = fileName.substring(fileName.lastIndexOf(".") + 1);
        System.out.println(substring1); //输出png

    }
}

Test Results:

Guess you like

Origin blog.csdn.net/weixin_53142722/article/details/127036315