Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow empty strings in String.split()? [duplicate]

Tags:

java

string

split

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?

like image 775
Bart Friederichs Avatar asked May 28 '15 14:05

Bart Friederichs


People also ask

Can you split an empty string?

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.

What happens when split empty string?

If the delimiter is an empty string, the split() method will return an array of elements, one element for each character of string.

Can split return an empty array?

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.

Does split () alter the original string?

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.


1 Answers

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.

like image 82
Mena Avatar answered Oct 19 '22 13:10

Mena