Java split string to array

Java split string to array

This behavior is explicitly documented in String.split(String regex) (emphasis mine):

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

If you want those trailing empty strings included, you need to use String.split(String regex, int limit) with a negative value for the second parameter (limit):

String[] array = values.split(\|, -1);

Try this

String[] array = values.split(\|,-1); 

Java split string to array

Consider this example:

public class StringSplit {
  public static void main(String args[]) throws Exception{
    String testString = Real|How|To|||;
    System.out.println
       (java.util.Arrays.toString(testString.split(\|)));
    // output : [Real, How, To]
  }
}

The result does not include the empty strings between the | separator. To keep the empty strings :

public class StringSplit {
  public static void main(String args[]) throws Exception{
    String testString = Real|How|To|||;
    System.out.println
       (java.util.Arrays.toString(testString.split(\|, -1)));
    // output : [Real, How, To, , , ]
  }
}

For more details go to this website: http://www.rgagnon.com/javadetails/java-0438.html

Leave a Reply

Your email address will not be published. Required fields are marked *