CSV – Count #Columns

At start I count number of comma, like:

stream.forEach(csvLine -> {
    int commaCounter = countMatches(csvLine, ",");
    if (commaCounter != FIELDS_IN_CSV - 1) {
        // Alert
    }

but I found (thank you bug) that comma is a legal character when it surround by apostrophes, like "This is one, value".

I look for a short way to solve it but found nothing (using openCsv library, if it’s help).

of course, I can iterate, enqueue/dequeue the apostrophes* to a stack and count the separate comma. does here a short way to do it?

  • or increase / decrease apostrophes counter value

Answer

A simple do it yourself solution would be:

int getFieldCount( String csvLine )
{
    char[] ch = csvLine.toCharArray();
    int len = ch.length, pos = 0, commaCounter = 0;
    while ( pos < len )
    {
        char c = ch[pos];
        if ( c == ',' ) commaCounter++;
        else if ( c == '"' )
        {
            pos++;
            while ( pos < len && ch[pos] != '"' ) pos++; // skip everything until the end of the string (or line)
        }
        pos++;
    }
    return commaCounter;
}

Something like the above should work 😉

Leave a Reply

Your email address will not be published. Required fields are marked *