1

I'm trying to convert a string into an array using the split(";"). I do so:

String str = "ggg;123;q;w;;";
String[] strArr = str.split(";");

Returns array:

["ggg","123","q","w"]

But I want to be returned:

["ggg","123","q","w","",""]

Strings may be "ggg;123;;w;;df" or "ggg;123;;;ds;".

I want to create an empty element in the array when there is no value between ";". This is possible to do?

Thanks for the help!

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
Cocuckalol
  • 34
  • 2
  • 5

3 Answers3

7

Use like that

String[] strArr = str.split(";",-1);
System.out.println(Arrays.toString(strArr));
Braj
  • 46,415
  • 5
  • 60
  • 76
Siva Kumar
  • 1,983
  • 3
  • 14
  • 26
1

If you take a look at documentation of split(String regex) you will find (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.

Now if you got to this two argument split(String regex, int limit) method documentation you will find that

If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

So to prevent removing trailing empty strings and not limiting length of result array you need to use non-positive value as limit so instead of

split(";")

use

split(";", -1)
Pshemo
  • 122,468
  • 25
  • 185
  • 269
1

A more readable alternative is provided by the Guava library.

By default, empty strings are included.

    String str = "ggg;123;q;w;;";
    List<String> split = Splitter.on(";").splitToList( str );

Empty strings can be omitted with a readable method name:

    String str = "ggg;123;q;w;;";
    List<String> split = Splitter.on(";").omitEmptyStrings().splitToList( str );
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151