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

Splitting by the string "malloc" isn't working and returns a different split

char str[2500] ="int *x = malloc(sizeof(int));";
    const char s[9] = "malloc";
    char *token = strtok(str, s);

    while( token != NULL ) {
      printf("%s\n", token );
    
      token = strtok(NULL, s);
    }

Output:

int *x = 
(size
f(int));

I want it to return:

int *x = 
(sizeof(int));

but oddly it refuses to do that and I can’t seem to figure out why it’s doing that.

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

edit: I realized that the size is too small, but still has a problem.

>Solution :

The second parameter of the function strtok means that any character present in the string can be used as a terminating character.

So this substring

(sizeof(int))

is terminated as soon as the character ‘o’ present in the string "malloc" is found.

What you need to use is the standard C string function strstr. It will find the sub-string "mallpc" in the source string and you will be able to output the sub-strings before "malloc" and after it.

For example

char str[2500] ="int *x = malloc(sizeof(int));";
    const char s[9] = "malloc";
    char *p = strstr(str, s);

    if ( p != NULL )
    {
        printf( "%.*s\n", ( int )( p - str ), str );
        if ( p[strlen( s )] != '\0' ) puts( p );
    }
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