6

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?

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195

3 Answers3

9

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.

Mena
  • 47,782
  • 11
  • 87
  • 106
0

You could simply loop through the array afterwards and assign empty strings as null:

public class StringSplitting {

    public static void main(String[] args){

        String inputs = "[data]<US><US>[data]<US>";

        String[] fields = inputs.split("<US>");


        //set empty values to null
        for(int i = 0; i < fields.length; i++){
            if(fields[i].length() == 0){
                fields[i] = null;
            }
        }

        //print output
        for(String e: fields){
            if(e == null){
                System.out.println("null");
            }else{
                System.out.println(e);
            }
        }
    }
}
Loco234
  • 521
  • 4
  • 20
-1

This is a working code

String s="[DATA]<US><US>[DATA]<US>";
String arr []= s.split("<US>");
for(String str :arr) {
    if(str.equals("")) {
        System.out.println("null");
    } else {
        System.out.println(str);
    }       
}

Output::

[DATA]
null
[DATA]

To be more specific as per your requirement:

public String [] format(String s) {     
        String arr []= s.split("<US>");     
        for(int i=0;i<arr.length;i++)
        {
            if(arr[i].equals(""))
            {
                arr[i]=null;
            }           
        }
        return arr;
    }
Oliver
  • 6,152
  • 2
  • 42
  • 75