frazman
frazman

Reputation: 33293

How to properly split a line in java

I am bit confused

 public static void main(String [] args){
        String s = "a,b,c,d,";

        System.out.println(s.split(",").length);
    }

I was expecting to see 5 as output.. but the output is 4? Why does it ignores the last "null" field

How do I handle this case if I am trying to parse data which has (say) 5 columns.

cases:
a,b,c,d,e
a,,c,d,e //this case is fine as this still has 5 fields.. one of the field is missing.. but thats ok
a,b,c,d //simple length check with header catches this error
a,b,c,d,e,f //simple length check
a,b,c,d,e,// looks like there are 6 fields.. but unable to catch such error by length check

Upvotes: 1

Views: 285

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213361

String#split() method ignores any trailing empty string. So, they are not the part of the array. If you want them to be the part of array, use the overloaded split(String, int) method, which takes a limit as 2nd argument. If you pass a negative value for the limit, the trailing empty strings won't be ignored.

System.out.println(s.split(",", -1).length);

And also, an empty string is not null.

Upvotes: 8

Related Questions