I am trying to split a string using String split function, here's an example:
String[] list = " Hello ".split("\\s+");
System.out.println("String length: " + list.length);
for (String s : list) {
System.out.println("----");
System.out.println(s);
}
Here's the output:
String length: 2
----
----
Hello
As you can see, the leading whitespace becoming an empty element in the String array, but the trailing whitespace is not.
Does anyone know why?
From split documentation
so in reality
split(regex)
is the same as usingand its documentation says
so if you want to include trailing empty strings will just have to use non-zero value like
but this will also limit result array to max 10 elements. To get rid of this problem use some negative number like
You need to use the other split method which specifys the limit and specify a limit of
-1
to preserve the trailing whitespace, - the default behavior is to omit the trailing spaces as per the javadoc
Edit (answer for comment):
To trim the leading space, you can strip off the leading space before splitting the
String