How to keep empty field when splitting string in Java

I’m not much working with Java, but recently when working with XPages, I have a chance to be more fluent with its SSJS and Java bean. Today there was a small problem that took me quite a long time to figure out, so I think this post may help others that face similar problem like me.

 

I have an tab-delimiter text file which is exported from Excel, and I want to import to my Lotus Domino document. It was easy until I need to split the string to get a specific column, and I found out the the split() function doesn’t keep my empty field!

 

What does that mean?

If you have a string like this:

String row = "\t\t";;
String[] columns = row.split("\t");

If you check the size of columns variable, it is zero

System.out.println(columns.length) // = 0

So what to do if we want to get the empty string also, luckily there’s a way, and it’s simple like this:

String[] columns = row.split("\t", -1);

Now, check out the size of the array, it will have 2 elements, each is an empty string

System.out.println(columns.length) // = 2

Related posts:

Share

About number.0