Case 1
String a = " ";
String[] b = a.split(",");
System.out.println(b.length);
Prints 1. Why?
Case 2
String a = ",,,,,,,,,,,,";
String[] b = a.split(",");
System.out.println(b.length);
Prints 0. Why?
Honestly, i am at a loss here
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This behaviour is mentioned in the documentation for String.split:
Your first example should give an array containing a single string containing spaces. A string containing spaces is not empty so it is included in the result.
Your second example would give an array containing lots of empty strings, but these are not included in the resulting array as mentioned in the documentation.
As to why the Java designers decided that removing trailing empty strings when
limitis zero is a good idea – I don’t know. Most other programming languages / platforms do not do this. I consider it to be a “gotcha” – a feature that doesn’t quite work as most people expect.