2

I have found this strange behavior by trying to write a unit test against a CSV Generator. It seems that if I try to split a string by comma, and there is an empty trailing cell, these values are ignored. Oddly, leading empty cells are fine. Is this behavior a bug? Should I be using a different expression than ,? Is there a version where it works as I expect?

Script

Integer repro(String commaSeparated)
{
    return commaSeparated.split(',').size();
}
system.debug('Should be 2: ' + repro('2,'));
system.debug('Should be 3: ' + repro(',,3'));

Log

USER_DEBUG [5]|DEBUG|Should be 2: 1
USER_DEBUG [7]|DEBUG|Should be 3: 3

  • 2
    Always love to see a drive by down vote with no explanation. – Adrian Larson Apr 16 at 17:51
4

According to the documentation String Class, here you need to pass the limit which is optional one.

The optional limit parameter controls the number of times the pattern is applied and therefore affects the length of the list.

If limit is greater than zero: - The pattern is applied a maximum of (limit – 1) times. - The list’s length is no greater than limit. - The list’s last entry contains all input beyond the last matched delimiter.

If limit is non-positive, the pattern is applied as many times as possible, and the list can have any length.

If limit is zero, the pattern is applied as many times as possible, the list can have any length, and trailing empty strings are discarded.

So, passing -1 as limit in this split(regExp, limit) method gives me desired results.

Integer repro(String commaSeparated)
{
   return commaSeparated.split(',',-1).size();
}
system.debug('Should be 2: ' + repro('2,'));
system.debug('Should be 3: ' + repro(',,3'));
  • N.B. this behavior is version dependent, if I recall correctly. Previously, it worked like it did in Java 7, but was then changed to work like it does in Java 8. I don't recall where the version change happened, probably 28.0 or 32.0, but definitely worth paying attention to release notes and testing on the selected API version. – sfdcfox Apr 3 at 6:26
  • I have checked that at current version 45.0, it is perfectly working – Santanu Boral Apr 3 at 7:07
  • 2
    Yes, but not all classes in an org might be at the same version. It's simply a word of caution for those that depend on this answer without checking the API version. – sfdcfox Apr 3 at 7:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.