Search code examples
csplitsegmentation-faultc-stringsstrtok

C - How to split a string with delimiter when sometimes there are no values between delimiter?


I am trying to split a string as follows: 1.97E+13,1965.10.30,12:47:01 AM,39.1,23,greece,,,,,10,4.8,4.6,4.6,4.8,4.6,4.7

I am using strtok and giving , as a delimiter but since there are no values between some commas I get a segmentation fault.

What is the correct way to assign null values to consecutive commas?


Solution

  • Instead of strtok use functions strspn and strcspn.

    Here is a demonstration program.

    #include <stdio.h>
    #include <string.h>
    
    int main( void )
    {
        const char *s = "1.97E+13, 1965.10.30, 12:47 : 01 AM, 39.1, 23, "
            "greece, , , , , 10, 4.8, 4.6, 4.6, 4.8, 4.6, 4.7";
    
        const char *delin = ",";
    
        for (const char *p = s; *p; p += *p != '\0')
        {
            size_t n = strcspn( p, delin );
            if (n == 0)
            {
                puts( "empty" );
            }
            else
            {
                printf( "\"%.*s\"\n", ( int )n, p );
            }
    
            p += n;
        }
    }
    

    The program output is

    "1.97E+13"
    " 1965.10.30"
    " 12:47 : 01 AM"
    " 39.1"
    " 23"
    " greece"
    " "
    " "
    " "
    " "
    " 10"
    " 4.8"
    " 4.6"
    " 4.6"
    " 4.8"
    " 4.6"
    " 4.7"