0

When I was trying to split a string using comma delimiter and string was having just two characters: a comma and a trailing space. After split the size of array is 2 but when I use string having a leading space and a comma, the size of array after split is 1. Can anyone please explain in details about this difference and its reason.

String s1 = ", ";
String s2 = " ,";
String[] str1 = s1.split(",");
String[] str2 = s2.split(",");
#str1 is of 2 size and str2 is of 1 size.

I can understand the reason of str2 size as 1 which is because split's default behaviour is to discard empty strings after delimiter but why the size of str1 is 2? Does it consider leading empty strings? If yes, when I take string with comma as the only character, why the size is 0? Does it not consider leading empty strings at that time?

  • Did you read the docs? – shmosel Feb 10 '23 at 08:21
  • It's size 1 and size 2 (not 0 and 1)! – knittl Feb 10 '23 at 08:22
  • Sorry for the typo. str1 size is 2 and str2 size is 1. str2 is clear as it has one space character. That's why the size is 1 but why the str1 size is 2? Considering that also has only one space character. I've now corrected the typo in the question as well. – Rohit Dhawan Feb 10 '23 at 08:35

0 Answers0