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 output as

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

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

+4
source share
5 answers

The first argument is actually not null; it is the empty string "" . The reason this is part of the output is because you split the empty string.

Split documentation says

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

Each position in your input line starts with an empty line (including position 0), so the split function also splits the input at position 0. Since there are no characters before position 0, this leads to an empty line 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 "positive zero-width lookbehind" that matches an arbitrary character ( . ). In words, he roughly "breaks into every empty line with some symbol in front of it."

+9
source

This quirk off String#split required string is actually a regular expression that matches the empty string that is at the beginning of the input.

try toCharArray() instead:

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

I will leave this as a reading exercise to convert the char[] array to String[]

+5
source

This is not empty, this is an empty string. This is an important difference!

You can get what you want using this construct:

  String[] tokens = "0110000".split("(?<=.)"; // the (?<=.) means that there must be a character // before the match, hence the initial empty string won't match System.out.println(Arrays.toString(tokens))); 

But I do not think this is a good idea. I cannot imagine why you want to split a String into an array of single-letter strings. You should probably use this:

 char[] chars = "001100".toCharArray(); 
+2
source

Because "" matches at the beginning of a line. It also matches at the end, but split() discards the final empty string.

+1
source

A line always starts with an empty line. An empty string contains no characters. You can check a similar question here .

0
source

All Articles