Search code examples
cstringtokenize

How to break a string in C with /


I have a string with the following pattern :

char *str = "ai/aj/module_mat.mod";

and I want to select module_mat as my final string for the further logic. I have tried to used rindex() so that I can get the final part of the string. But I am not able to do this in C. What am I doing wrong?

The code I am trying is -

char *first = rindex(str, "/");
char *first = strtok(first, ".");

Solution

  • Your mistake is right here:

    char *str = "ai/aj/module_mat.mod";
    

    Since str points to a constant, this should be:

    const char *str = "ai/aj/module_mat.mod";
    

    Now your compiler should show you the other problems.

    Similarly:

    char *first = rindex(str, "/");
    

    Since rindex is returning a pointer into the constant you passed it, that pointer should also be const.

    char *first = strtok(first, ".");
    

    Hmm, what do the docs for strtok say:

    If a delimiter byte is found, it is overwritten with a null byte to terminate the current token, and strtok() saves a pointer to the following byte; ...

    So strtok modifies the thing the pointer points to, so passing it a pointer to a constant is bad! You can't modify a constant.