Search code examples
csplitc-stringsstrtokstrstr

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.

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 );
        }