Reputation: 53
My code is
public class Main
{
public static void main(String[] args)
{
String inputString = "#..#...##";
String[] abc = inputString.trim().split("#+");
for (int i = 0; i < abc.length; i++)
{
System.out.println(abc[i]);
}
System.out.println(abc.length);
}
}
The output abc is an array of length 3. with abc[0] being an empty string. The other two elements in abc are .. and ...
If my inputString is "..##...". I don't get a empty string in the array returned by split function. The input String doesn't have trailing whitespace in both cases.
Can soemone explain me why do I get a extra space in the code shown above?
Upvotes: 1
Views: 99
Reputation: 81
Whenever you say .split to a String, it splits the String n number of times that condition is met.
So when you say
String inputString = "#..#...##";
and your condition for spliting is #
and since the value before the first occurrence of #
is empty
, abc[0]
will hold empty
. Therefore count of abc will return 3 because abc[0]=nothing(empty string), abc[1]=.. abc[2]=...
Upvotes: 0
Reputation: 12520
From the Javadoc:
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
And Javadoc:
If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
Upvotes: 0
Reputation: 16152
You don't get an extra space, you get the empty string (with length 0). It says so in the javadoc:
* <p> When there is a positive-width match at the beginning of this
* string then an empty leading substring is included at the beginning
* of the resulting array. A zero-width match at the beginning however
* never produces such empty leading substring
Upvotes: 1
Reputation: 786299
When you split by #+
and first character of input string is #
then input is split at beginning itself and what you get is an empty string as first element of string. It is due to the fact that left hand side of first #
is just anchor ^
which will give an empty string only in the resulting array.
Upvotes: 0