|
From: Anton S. <ant...@gm...> - 2017-04-09 13:56:47
|
I wrote:
> The interface of strtok_r() is rather ugly. Its
> first invocation shall differ from subsequent
> ones, whereas the task performed is the same.
>
> I have come up with more consistent version:
> [...]
The code fragment is broken because grofg interpret-
ed '\' as an escape character. Here is the correct
code:
/* returns the index of c in s, or -1 if not found */
/* s shall be a NULL-terminated string */
static int chrind( const char * s, const char c )
{ int res = -1;
int ind = 0;
while( s[ind] != '\0' )
{ if( s[ind] == c )
{ res = ind; break; }
ind++;
}
return res;
}
/* Re-entrant version with consistent invocation */
/* str and delim shall be NULL-terminated string */
static char * strtok_r2( char** str, const char *delim )
{ char tok_found = 0;
char is_del = 0;
char* res = NULL;
while( **str != '\0' )
{ is_del = chrind( delim, **str ) >= 0;
if( tok_found && is_del )
{ **str = '\0'; /* NULL-terminate in place */
( *str )++; /* and wind on to the next symbol */
break;
}
if( !tok_found && !is_del )
{ tok_found = 1;
res = *str; /* save start of token */
}
( *str )++;
}
return res;
}
--
Please, do not forward replies to my e-mail.
|