avoiding costly strtok call --- sscanf call an alternative

unsafe: strtok() modifies it's argument the string is subsequently unsafe and cannot be used in its original form. Use of strtok() should be avoided. This function cannot be used on constant strings.

Safe Use of strtok:
1. Check for null strings before the first call

2. Check the string is empty after the last call
The second is advisable, while the first is required, as strtok does not generally deal with null pointers very elegantly.
3. if possible, or if necessary, copy the original string into a buffer and pass the address of the buffer to strtok() instead of the original string.

4. avoid memory leaks, there will be char pointers used to copy to avoid overwriting.

Strtok is a costly call for (overwritng global variables and CPU time)

We can use sscanf for the same purpose.

using strtok( ) call,
char str[] ="first|25.5, , | |second|15";
char buff[100] = {0};
char *pch = NULL;
strcpy(buff,str);
printf("\nbuff:%s\n",buff);
pch = strtok (buff,"|");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, "|");
}

using sscanf() call call,

char str[] ="first|25.5, , | |second|15";
int result;
char o[10], f[10], s[10], t[100];
result = sscanf(str, "%[^'|']|%[^'|']|%[^'|']|%s", o, s, t, f);
printf("%s\n %s\n %s\n %s\n", o, s, t, f);


Here pipe a separator , if we want to delimit with a ; symbol,

sscanf(tokenstring, "%[^';'];%[^';'];%[^';'];%s", o, s, t, f);



No comments :

Post a Comment