Search code examples
cstrtok

C - Split string with repeated delimiter char into 2 substrings


I'm making a very simple C program that simulates the export command, getting an input with fgets().

Input example:

KEY=VALUE

Has to be converted to:

setenv("KEY", "VALUE", 1);

That's easy to solve with something similar to this code:

key = strtok(aux, "=");
value = strtok(NULL, "=");

The problem comes when the user input a value that start with one or several equals = characters. For example:

KEY===VALUE

This should be converted to:

setenv("KEY", "==VALUE", 1);

But with my current code it is converted to:

setenv("KEY", NULL, 1);

How I can solve this?

Thanks in advice.


Solution

  • Your second strtok() should not use = as the delimiter. You would only do that if there were another = that ended the value. But the value ends at the end of the string. Use an empty delimiter for this part.

    key = strtok(aux, "=");
    value = strtok(NULL, "");