TetaTricks/code/C/demo-strtok.c

58 lines
1.3 KiB
C
Raw Normal View History

2023-09-01 12:37:36 +02:00
/*
2023-10-08 21:56:41 +02:00
* +-------------+
* | demo strtok |
* +-------------+
2023-09-01 12:37:36 +02:00
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
2023-09-03 22:24:56 +02:00
/*-------------------------------------------------------*/
2023-09-01 12:37:36 +02:00
void dump_line(char *titre, char *ligne, int combien)
{
int foo;
unsigned char *ptr;
printf(" --- %s\n", titre);
ptr = (unsigned char *)ligne;
for (foo=0; foo<combien; foo++) {
2023-10-08 21:56:41 +02:00
if (ptr[foo]) printf("%02x ", ptr[foo]);
else printf("\\0 ");
2023-09-01 12:37:36 +02:00
}
puts("");
for (foo=0; foo<combien; foo++) {
2023-09-03 07:49:40 +02:00
printf(" %c ", isprint(ptr[foo]) ? ptr[foo] : ' ');
2023-09-01 12:37:36 +02:00
}
puts("");
}
2023-09-03 22:24:56 +02:00
/*-------------------------------------------------------*/
2023-09-01 12:37:36 +02:00
int main(int argc, char *argv[])
{
2023-09-03 07:49:40 +02:00
char input[] = "foo bar\tquux wiz";
2023-09-01 12:37:36 +02:00
char *cptr, *copie;
int foo;
dump_line("original", input, sizeof(input));
copie = strdup(input);
dump_line("copie", copie, sizeof(input));
puts("");
cptr = strtok(copie, " \t");
dump_line("1er strtok", copie, sizeof(input));
printf(" got [%s]\n", cptr);
puts("");
2023-09-03 07:49:40 +02:00
puts(" two more strtok...");
2023-09-01 12:37:36 +02:00
cptr = strtok(NULL, " \t");
2023-09-03 07:49:40 +02:00
printf(" got [%s]\n", cptr);
2023-09-01 12:37:36 +02:00
cptr = strtok(NULL, " \t");
2023-09-03 07:49:40 +02:00
printf(" got [%s]\n", cptr);
2023-09-01 12:37:36 +02:00
dump_line("2eme & 3me strtok", copie, sizeof(input));
2023-09-03 07:49:40 +02:00
foo = cptr - copie; /* this is the hack :) */
2023-09-01 12:37:36 +02:00
printf(" index = %d\n", foo);
2023-10-08 21:56:41 +02:00
printf(" and we have [%s] :)\n", input+foo);
2023-09-01 12:37:36 +02:00
return 0;
}