String # split behavior when splitting an empty string according to "\ s +"

I am new to Java. Unfortunately, there are many things in Java that are very difficult for beginners to understand.

For example,

String str = "";
String[] arr = str.split("\\s+");
System.out.println(Arrays.toString(arr));
System.out.println(arr.length);
System.exit(0);

Output signal

[]
1

But why? I would appreciate it if someone could explain to me why the length of the array is 1.

+4
source share
3 answers

Let's look at the implementation Arrays.toString:

public static String toString(Object[] a) {
    if (a == null)
        return "null";
    int iMax = a.length - 1;
    if (iMax == -1)
        return "[]";

    StringBuilder b = new StringBuilder();
    b.append('[');
    for (int i = 0; ; i++) {
        b.append(String.valueOf(a[i]));  // Let print that!
        if (i == iMax)
            return b.append(']').toString();
        b.append(", ");
    }
}

Now, since the array is not empty, we move on to the loop for. Let's start by adding [to the result. Then add String.valueOf(a[i]). Try to print it:

String str = "";
String[] arr = str.split("\\s+");
System.out.println(String.valueOf(arr[0]));

You will see that the conclusion ... nothing! So the end result:

[]

, Java 8. split .

+3

String , - String, "Nothing" - split(). .

str[0], . "" null, NullPointerException ( split() )

+10

enter image description here An empty string is present in the 1st place divided array.

public static void main(String[] args) {
        String str = "";
        String[] arr = str.split("\\s+");
        System.out.println(Arrays.toString(arr));
        System.out.println(arr[0]);
        System.out.println(arr.length);
        System.exit(0);
    }

Exit

[]

1
+7
source

Source: https://habr.com/ru/post/1609598/


All Articles