Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strtok c multiple chars as one delimiter

Is it possible to use multiple chars as one delimiter?

I would like a string as separator for another string.

char * input = "inputvalue1SEPARATORSTRINGinputvalue2SEPARATORSTRINGinputvalue2";
char * output = malloc(sizeof(char*));
char * delim = "SEPARATORSTRING";

char * example()
{
    char * ptr = strtok(input, delim);

    while (ptr != NULL)
    {
      output = strcat(output, ptrvar);
      output = strcat(output, "\n");
      ptr = strtok(NULL, delim);
    }

    return output;
}

Return value printed with printf:

inputvalue1
inputvalue2
inputvalue3
like image 323
it-person Avatar asked Dec 04 '25 15:12

it-person


1 Answers

No, according to the manual page for strtok():

The delim argument specifies a set of bytes that delimit the tokens in the parsed string.

If you want to use a multi-byte string as delimiter, there is no built-in function that behaves like strtok(). You would have to use strstr() instead to find occurrences of the delimiter string in the input, and advance manually.

Here's an example from this answer:

char *multi_tok(char *input, char *delimiter) {
    static char *string;
    if (input != NULL)
        string = input;

    if (string == NULL)
        return string;

    char *end = strstr(string, delimiter);
    if (end == NULL) {
        char *temp = string;
        string = NULL;
        return temp;
    }

    char *temp = string;

    *end = '\0';
    string = end + strlen(delimiter);
    return temp;
}
like image 135
Marco Bonelli Avatar answered Dec 07 '25 05:12

Marco Bonelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!