3

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
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
it-person
  • 98
  • 1
  • 11
  • 1
    `char * output = malloc(sizeof(char*));` is wrong. – Sourav Ghosh Jan 16 '20 at 13:44
  • Is it possible - yes. It is possible with `strtok` - no. You will need to use `strstr` lo locate your delimiter substring within the string to be searched, and then break the string based on the length of your delimiter string. Why? Any one of the characters in the `strtok` delim string is a delimiter. The fact that you have a lot of them doesn't make `strtok` combine all the delimiter characters into a single delimiter. You want to find the *substring* that is your delimiter string within the search string. That takes `strstr`. – David C. Rankin Jan 16 '20 at 17:28

1 Answers1

5

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;
}
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128