Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading