How to allow empty lines in String.split ()?

I use String.split() to split the string. The line that I get has the following structure:

 [data]<US>[data]<US> 

where <US> is the ASCII unit separator (code 0x1F). Split code

 String[] fields = someString.split(String.valueOf(0x1f)); 

This works fine if [DATA] not an empty string. In this case, the data is simply skipped.

I want a string like [DATA]<US><US>[DATA]<US> return an array with three elements: [DATA] , null and [DATA] .

How can i do this?

+6
source share
3 answers

If you parameterize your split with -1 as the second argument, you will get an empty String where [data] missing (but not null ).

 someString.split(String.valueOf(0x1f), -1); 

Explanation from docs

If n is not positive, the pattern will be applied as many times as possible, and the array can be of any length.

.. where n is the limit, i.e. second argument.

+8
source

This is 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; } 
0
source

After that, you can simply skip the array and set the empty lines to 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); } } } } 
0
source

Source: https://habr.com/ru/post/988099/


All Articles