00 Votes

Java: Keep empty fields in Split-Array

Tip by Stefan Trost | 2013-09-25 at 16:08

When using the split function in Java in order to separate a string at a given character, by default, the resulting array does not contain any empty fields.

In some cases - for example when reading and editing CSV files containing empty columns - that is not wanted. That is why, I would like to show you in this tip how to keep the empty fields also in Java:

String s = "1;;3;4";

String[] r1 = s.split(";");       // -> "1", "3", "4"
String[] r2 = s.split(";", -1);   // -> "1", "", "3", "4"

As we can see from this example, the trick is to pass a -1 as the second parameter. The second parameter normally specifies the limit of the resulting array - that is the number of how many parts of the string should be separated maximally.

ReplyPositiveNegative

About the Author

AvatarYou can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.