开发者

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

开发者 https://www.devze.com 2023-01-29 00:19 出处:网络
public static void main(String args[]) { String sub=\"0110000\"; String a[]=sub开发者_运维问答.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?


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".


It's a quirk off String#split the string it takes is actually a regular expression which matches the empty string that is at the beginning of your input.

try toCharArray() instead:

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

I'll leave it as a exercise for the reader to convert the char[] array into String[]


It's not null, it's an empty string. That's an important distinction!

You can get what you want by 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 don't think that's a good idea. I can't imagine why you want to split a String into an array of one-letter Strings. You probably should use this instead:

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


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


A String always start with an empty string. An empty string contains no characters. You can check the similar question here.

0

精彩评论

暂无评论...
验证码 换一张
取 消