I am using String.split()
to split a string. The string I receive has this structure:
[data]<US>[data]<US>
where <US>
is the ASCII unit separator (code 0x1F). The code to split is
String[] fields = someString.split(String.valueOf(0x1f));
This works fine, unless [DATA]
is an empty string. In that case, data just gets skipped.
I want a string like [DATA]<US><US>[DATA]<US>
to return an array with three elements: [DATA]
, null
and [DATA]
.
How can I do that?
You can split a string by each character using an empty string('') as the splitter. In the example below, we split the same message using an empty string. The result of the split will be an array containing all the characters in the message string.
If the delimiter is an empty string, the split() method will return an array of elements, one element for each character of string.
Using split()When the string is empty and no separator is specified, split() returns an array containing one empty string, rather than an empty array. If the string and separator are both empty strings, an empty array is returned.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string.
If you parametrize your split
with -1
as a second argument, you'll get an empty String
where [data]
is missing (but not null
).
someString.split(String.valueOf(0x1f), -1);
Explanation from the docs
If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.
.. where n is the limit, i.e. the second argument.
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