Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Array length is showing 1 even the array is empty after call split by comma (,) [duplicate]

Tags:

java

arrays

Here is my code:

serialNumbers = "";

String[] serialArray = serialNumbers.split(",");

int arrayLength = serialArray.length;

arrayLength is showing 1 even there have no value in serialArray. I was expecting that length should return 0 in this case.

like image 372
ray Avatar asked Jul 15 '13 13:07

ray


People also ask

Why does split return empty string?

In the case of splitting an empty string, the first mode (no argument) will return an empty list because the whitespace is eaten and there are no values to put in the result list. In contrast, the second mode (with an argument such as \n ) will produce the first empty field.

Does an empty array have a length?

length property. If the length of the object is 0, then the array is considered to be empty and the function will return TRUE.

What happens when split empty string?

Using split() When the string is empty and no separator is specified, split() returns an array containing one empty string, rather than an empty array. If the string and separator are both empty strings, an empty array is returned.

How do you split a comma in a string?

To split a string with comma, use the split() method in Java. str. split("[,]", 0); The following is the complete example.


1 Answers

From the doc:

If the expression does not match any part of the input then the resulting array has just one element, namely this string.

Note that this doc is from the String.split(String, int) method, which is invoked from String.split(String)

like image 88
Brian Agnew Avatar answered Nov 15 '22 14:11

Brian Agnew