Home > Mobile >  How to use strtok in C if delimiter is defined as character
How to use strtok in C if delimiter is defined as character

Time:07-02

I'm trying to use strtok for a school assignment of mine, but the delimiter declared as a constant in the code is declared as a character, and I'm not allowed to change this. This delimiter is supposed to be arbitrary and has to work for any value. When I try to use strtok however, it expects a string. What is a workaround for splitting up strings when the delimiter is strictly defined as a single char in C?

CodePudding user response:

You can use compound literal for that.

Examples:

token = strtok(str, (char[]){'a',0});

or

const char delim = 'a';

token = strtok(str, (char[]){delim,0});

or if you need to use more chars you can define a macro

#define MKS(...) ((char[]){__VA_ARGS__, 0})

/* ... */

    token = strtok(str, MKS('a', 'b', 'c', ','));

CodePudding user response:

If you have a character constant like for example

const char c = ' ';

then to use strtok you can declare a character array like

char delim[] = { c, '\0' };

or that is the same

char delim[2] = { c };

In fact you can write your own function strtok using the character and the function strchr.

Here is a demonstration program.

#include <stdio.h>
#include <string.h>

int main( void )
{
    char c = ' ';
    char s[] = "Hello World";

    char *start = s, *end = NULL;
    do
    {
        end = strchr( start, c );
        if ( end != NULL )
        {
            if ( end != start )
            {
                *end = '\0';
                puts( start );
            }

            start = end   1;
        }
        else if ( *start )
        {
            puts( start );
        }
    } while ( end != NULL );
}

The program output is

Hello
World
  • Related