ss2
ss2

Reputation: 113

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.

Upvotes: 0

Views: 64

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311018

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

Upvotes: 2

dbush
dbush

Reputation: 223992

The second parameter to strtok is a list of characters which serve as delimiters. It is not a complete string used as a delimiter. So what you actually have is the characters 'm', 'a', 'l', 'o', and 'c' as delimiters, so anyplace one of those characters appears splits the string.

What you want instead is to use strstr to search for a substring. Then you can use that to copy from the start of str to the start of the substring, then copy again from the end of the substring to the end of str.

Upvotes: 3

Related Questions