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

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

why first element null? how can array without null @ beginning?

the first argument not null, empty string "". reason why part of output split on empty string.

the documentation of split says

the array returned method contains each substring of string terminated substring matches given expression or terminated end of string.

each position in input string starts empty string (including position 0) split function splits input @ position 0. since no characters in front of position 0, results in empty string first element.

try instead:

string sub = "0110000"; string a[] = sub.split("(?<=.)"); system.out.println(arrays.tostring(a)); 

output:

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

the pattern (?<=.) "zero-width positive lookbehind" matches arbitrary character (.). in words says "split on every empty string character in front of it".


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -