Discussion on the problem of java ES1en. split losing the empty ending string

  • 2020-06-15 08:25:50
  • OfStack

The split function in java is handy for splitting strings into character arrays, but it makes an error because it's not familiar

As follows:


String strtest   = "1,2,";
String arry[]  = strtest.split(",");

So the number of elements in the array is only 2, why? The last one "," has no content, it doesn't become the third element as an empty string, the empty string at the end is discarded!

This function also has another overload: public String [] split (String regex, int limit). See how many times the limit parameter controls the number of times the pattern is applied, thus affecting the length of the resulting array. If the limit n is greater than 0, the pattern will be applied up to es19EN-1 times, the array length will not be greater than n, and the last entry of the array will contain all input beyond the last matched delimiter.

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

For the function public String [] split (String regex), this method calls the two-parameter split method with the given expression and the limited argument 0. Therefore, the resulting array does not include an empty ending string

So if you don't want the empty string at the end to be discarded, write this:


String strtest    = "1,2,";
String arry[]  = strtest.split(",", -1);


Related articles: