自己动手很容易,真的:
#include <string.h>
typedef struct {
const unsigned char *data;
size_t len;
} buffer_t;
/* Use strpbrk() for multiple delimiters. */
buffer_t
memtok(const void *s, size_t length, const char *delim, buffer_t *save_ptr)
{
const unsigned char *stream,
*token;
size_t len = 0;
if (NULL == s) {
stream = save_ptr->data;
} else {
stream = s;
save_ptr->len = length;
}
token = stream;
/* Advance until either a token is found or the stream exhausted. */
while (save_ptr->len--) {
if (memchr(delim, *stream, strlen(delim))) {
/* Point save_ptr past the (non-existent) token. */
save_ptr->data = stream + 1;
return (buffer_t) { .data = token, .len = len };
}
++len;
++stream;
}
/* State : done. */
*save_ptr = (buffer_t) { .data = NULL, .len = 0 };
/* Stream exhausted but no delimiters terminate it. */
return (buffer_t){ .data = token, .len = len };
}
并进行简短测试:
int main(int argc, char **argv)
{
const char *the_sting = "a|b||e|f";
buffer_t kek = { .data = the_sting, .len = 8 },
token, state;
token = memtok(the_sting, 8, "|", &state);
while (token.data != NULL) {
char test[512];
memcpy(test, token.data, token.len);
test[token.len] = 0;
printf("%s\n", test);
token = memtok(NULL, 0, "|", &state);
}
return 0;
}