Why does System.out.println print a new line and System.out.print does not print anything?

I'm having problems with the split function. I do not know how this works.

Here is my source code:

// Using println to print out the result
String str  = "         Welcome       to    Java     Tutorial     ";
str = str.trim();
String[] arr = str.split(" ");
for (String c : arr) {
    System.out.println(c);
}

//Using print to  print out the result
String str  = "         Welcome       to    Java     Tutorial     ";
str = str.trim();
String[] arr = str.split(" ");
for (String c : arr) {
    System.out.print(c);
}

and results: Result

The first result is when using println, the second is the result when using print,

I do not understand why the space appears in println, but it does not appear in print. Can anyone explain this to me?

+4
source share
3 answers

Since you have many spaces in your line, if you look at the result of the split function, the resulting array will look like

[Welcome, , , , , , , to, , , , Java, , , , , Tutorial]

So if you look, they are empty. String "".

println(""), .

, print(""), , .

, .

, trim() String. .

+10

, , . , , , . , :

String[] arr = str.split("\\s+");

, .

, print println, . , cann println(""), .

+4

println() , print() .

, (""), , , . , , . , , : "" this. :

System.out.println("");

, print(), .

. : \\s+

, :

String[] arr = str.split("\\s+");
0
source

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


All Articles