I have a need to split a string that is passed in to my app from an external source. This String is delimited with a caret "^"
and here is how I split the String into an Array
String[] barcodeFields = contents.split("\\^+");
This works fine except that some of the passed in fields are empty and I need to account for them. I need to insert either ""
or "null"
or "empty"
into any missing field.
And the missing fields have consecutive delimiters. How do I split a Java String into an array and insert a string such as "empty"
as placeholders where there are consecutive delimiters?
The answer by mureinik is quite close, but wrong in an important edge case: when the trailing delimiters are in the end. To account for that you have to use:
contents.split("\\^", -1)
E.g. look at the following code:
final String line = "alpha ^beta ^^^";
List<String> fieldsA = Arrays.asList(line.split("\\^"));
List<String> fieldsB = Arrays.asList(line.split("\\^", -1));
System.out.printf("# of fieldsA is: %d\n", fieldsA.size());
System.out.printf("# of fieldsB is: %d\n", fieldsB.size());
The above prints:
# of fieldsA is: 2
# of fieldsB is: 5
String.split
leaves an empty string (""
) where it encounters consecutive delimiters, as long as you use the right regex. If you want to replace it with "empty"
, you'd have to do so yourself:
String[] split = barcodeFields.split("\\^");
for (int i = 0; i < split.length; ++i) {
if (split[i].length() == 0) {
split[i] = "empty";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With