Home > Net >  Find delimiter in strtok()
Find delimiter in strtok()

Time:12-30

I am new to C programming. I am trying to split a string using strtok(), using multiple delimiters. The line of code is :

char *token = strtok(st, "  -*/^()");

I want to know at which delimiter it got split. Is it possible? Please help. I mean in this example whether the token got split at space, plus, minus, etc.

CodePudding user response:

The function strtok changes the found delimiter by the zero character '\0'. So it is impossible to determine what delimiter was encountered.

Instead of the function strtok you can use functions strspn and strcspn. Using these functions you can determine what delimiter was encountered.

For example

size_t n = strcspn( st, "  -*/^()" );

if ( st[n] != '\0' )
{
    switch ( st[n] )
    {
    case ' ':
       //...
       break;
    case ' ':
       //...
       break;
    //...
    }
}
  
  • Related