1

Input

String str = ',,,,,,,af,afs,,,,,,,,,,,,,,,,,,';

List<String> strSplit = str.split(',');

System.debug(strSplit.size());

Result

USER_DEBUG|[5]|DEBUG|9

Input

String str = ',,,,,,,af,afs,,,,,,,,,,,,,,,,,,q';

List<String> strSplit = str.split(',');

System.debug(strSplit.size());

Result

USER_DEBUG|[5]|DEBUG|27

Edit: Same happens when I try to run similar code in Java.

3 Answers 3

5

When you don't know how many tokens, you can use this - note -1 as arg #2

String s = ',,,,,,,af,afs,,,,,,,,,,,,,,,,,,';
system.debug(LoggingLevel.iNFO,'#tokens=' + s.split(',',-1).size());
system.debug(LoggingLevel.iNFO,'#tokens=' + s.split('\\,',-1).size());

Both produce 27 tokens

The doc is covered here in this useful stackoverflow post

2

I believe it is correct. From Java documentation.

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.

Since the trailing strings are empty in first case, hence they are not included in the list.

In second case, the trailing string is not blank. It is 'q'.

Java Doc

1

I can't point you to the documentation confirming this but can suggest a work around. If you always expect your string to contain 27 comma-seprated values, use str.split(',', 27); instead - this will always create list with 27 items, even if all of them are empty.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .