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.
About the Author
You 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
PHP: Remove all empty elements from string array
Tip | 0 Comments
How to Replace multiple Texts at the same Time
Tutorial | 0 Comments
Send Form Input as an Array to PHP Script
Tip | 0 Comments
JavaScript: Create and Use Arrays
Info | 0 Comments
Lazarus: Load File as Byte Array and save Byte Array as File
Tutorial | 0 Comments
JavaScript: Remove last character from string
Tip | 5 Comments
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.