Java split string to array

JavaStringSplit

Java Problem Overview


I need help with the split() method. I have the followingString:

String values = "0|0|0|1|||0|1|0|||";

I need to put the values into an array. There are 3 possible strings: "0", "1", and ""

My problem is, when i try to use split():

String[] array = values.split("\\|"); 

My values are saved only until the last 0. Seems like the part "|||" gets trimmed. What am i doing wrong?

thanks

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

Try this

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

Solution 3 - Java

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

Solution 4 - Java

This is expected. Refer to Javadocs for split.

Splits this string around matches of the given regular expression.

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDusanView Question on Stackoverflow
Solution 1 - JavaMark RotteveelView Answer on Stackoverflow
Solution 2 - JavaLokeshView Answer on Stackoverflow
Solution 3 - JavaS. MayolView Answer on Stackoverflow
Solution 4 - JavaSrinivasView Answer on Stackoverflow