Nawaz
Nawaz

Reputation: 413

Java split stops at white space while using | as delimiter

I am splitting a String with split() but I don't know why it stops when it reaches a whitespace. Here is the code:

String a = "R|1|^^^fieldname1|18.8H |||||||||";

String[] b = a.split(Pattern.quote("|"));
also tried
String[] b = a.split("\\|");

System.out.println("Array length :"+b.length);

Output is : 4

I could not find a reason behind this please suggest me what am I missing.

Upvotes: 2

Views: 1585

Answers (2)

AxelH
AxelH

Reputation: 14572

From the javadoc :

String.split(String pattern, int limit)

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. 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.

You can see the code of split :

public String[] split(String regex) {
    return split(regex, 0);
}

This is normal that the lqst empty values are removed, the limit is 0.

If you pass -1, this will take every empty value. No right triming is done on the empty cells.

String a = "R|1|^^^fieldname1|18.8H|||||||||";
String[] b = a.split("\\|", -1);
System.out.println(b.length);

With an output of

 13

Upvotes: 1

Adam Arold
Adam Arold

Reputation: 30528

If you read the documentation of split it says:

This method works as if by invoking the two-argument {@link#split(String, int) split} method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

Since you have empty Strings between your last |s they are not included in the result.

If you try this:

String a = "R|1|^^^fieldname1|18.8H | | | | | | | | |";

String[] b = a.split("\\|");

System.out.println(Arrays.deepToString(b));

The result will be:

[R, 1, ^^^fieldname1, 18.8H ,  ,  ,  ,  ,  ,  ,  ,  ]

Hope this helps.

Upvotes: 0

Related Questions