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?

0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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);
            }
        }
    }
}

Comments

-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;
    }

2 Comments

My point was that this in fact does not work. There are no empty strings when no limit is supplied.
@BartFriederichs Please elborate. What do you mean by no limit?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.