简体   繁体   中英

Why does System.out.println print a new line while System.out.print prints nothing?

I am having trouble with split function. I do not know how it 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 the results are: 结果

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

I do not understand why space appears in println , while it does not appear in print . Can anyone explain it for me?

Since you have many spaces in your string, if you look at the output of split function, the resulted array looks like

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

So if you look close they are empty String's "" .

When you do a println("") it is printing a line with no string.

However when you do print("") , it is no more visibility of that string and it looks nothing getting printed.

If you want to separate them regardless of spaces between them, split them by white space.

Lastly, trim() won't remove the spaces within the String. It can only trim spaces in the first and last.

What you are doing is splitting by every individual white space. So for every space you have in your string, it is split as a separate string If you want to split just the words, you can use the whitespace regex:

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

This will fix your problem with the consecutive whitespaces you are printing.

Also, When you use print instead of println your print value DOES NOT carry over to the next line. Thus when you cann println("") you are just going to a new line.

println() method prints everything in a new line but the print() method prints everything in the same line.

So, when you are splitting your string by space(" ") then, for the first one, the string is splitting for every space. So, every time a new line comes while printing. You can't see anything just the new line because you are printing: "" this. Because your code is:

System.out.println("");

But for the second one, the string is splitting for every space but you are using print() method that's why it's not going to the new line.

You can overcome this by regex. You can use this regex: \\\\s+

So, you have to write:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM