Java string Split() deletes trailing empty entries

I'm trying to parse some pipe delimited records I have this Code:

public class Test {
    public static void main(String[] args) throws Exception {
        String[] components = "EN|1056209|||KA3NDL|L|||||||||||||||||||||".split("\\|");
        System.out.println(java.util.Arrays.toString(components));
    }
}

You want it to print:

[EN,1056209,KA3NDL,L,]

But this is not the case It prints:

[EN,L]

Accessing the length property of the components array indicates that it is printing correctly

Anyone knows why this is a solution?

Edit:

This works:

public class Test {
    public static void main(String[] args) throws Exception {
        String[] components = "EN|1056209|||KA3NDL|L|||||||||||||||||||||".split("\\|",-1);
        System.out.println(java.util.Arrays.toString(components));
    }
}

Solution

String without limit parameter Split removes all trailing empty strings from the result array You need to include a restriction:

String str = "EN|1056209|||KA3NDL|L|||||||||||||||||||||";
String[] components = str.split("\\|",-1);

From string Start with split (string, int):

Call string Split (string) is equivalent to calling a 2 parameter split with a limit of 0

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>