Search code examples
cstringstrtokstring-literals

srtok is not working in c


here is my code,

#include <string.h>
#include <stdio.h>

main ()
{
    explode (" ", "this is a text");
}

    explode (char *delimiter, char string[])
{
char *pch;
printf ("Splitting string \"%s\" into tokens:\n",string);
pch = strtok (string,delimiter);
while (pch != NULL)
{
    printf ("%s\n",pch);
    pch = strtok (NULL, delimiter);
}
return 0;
}

I compile this code using gcc -o 1.exe 1.c and shows no error. But when i execute 1.exe it shows Splitting string "this is a text" into tokens: and at that moment 1.exe stops working (a dialogue box of windows shows). can anybody tell the problem and solve the problem? I am using windows 10.


Solution

  • While you can't do this with strtok because the literal can't be modified, it can be done with strcspn.

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    void explode (char *delimiter, char *string);
    
    int main()
    {
        explode (" ", "this is a text");
        return 0;
    }
    
    void explode (char *delimiter, char *string)
    {
        int span = 0;
        int offset = 0;
        int length = 0;
    
        if ( delimiter && string) {
            length = strlen ( string);
            printf ("Splitting string \"%s\" into tokens:\n",string);
            while (offset < length) {
                span = strcspn ( &string[offset],delimiter);//work from offset to find next delimiter
                printf ("%.*s\n",span, &string[offset]);//print span number of characters
                offset += span + 1;// increment offset by span and one characters
            }
        }
    }