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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With