Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an array of all 1 character long substrings of a given String using split

public static void main(String args[]) {
    String sub="0110000";
    String a[]=sub.split("");
    System.out.println(Arrays.toString(a));
}

I get the output as

[, 0, 1, 1, 0, 0, 0, 0]

Why is the first element null? How can I get an array without null at the beginning?

like image 225
elle Avatar asked Dec 03 '22 10:12

elle


1 Answers

The first argument is actually not null, it is the empty string "". The reason why this is part of the output is that you split on the empty string.

The documentation of split says

The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string.

Each position in your input string starts with an empty string (including position 0) thus the split function also splits the input at position 0. Since no characters are in front of position 0, this results in an empty string for the first element.

Try this instead:

String sub = "0110000";
String a[] = sub.split("(?<=.)");
System.out.println(Arrays.toString(a));

Output:

[0, 1, 1, 0, 0, 0, 0]

The pattern (?<=.) is a "zero-width positive lookbehind" that matches an arbitrary character (.). In words it says roughly "split on every empty string with some character in front of it".

like image 174
aioobe Avatar answered Dec 05 '22 22:12

aioobe