您可能不想strtok
开始,因为它使您无法确定消除了哪个字符(除非您有字符串的备用副本)。
strtok
不是一个简单的 API,很容易被误解。
引用手册页:
The strtok() and strtok_r() functions return a pointer to the beginning of
each subsequent token in the string, after replacing the token itself with
a NUL character. When no more tokens remain, a null pointer is returned.
您的问题可能意味着您已经陷入算法的默默无闻。假设这个字符串:
char* value = "foo < bar & baz > frob";
第一次打电话strtok
:
char* ptr = strtok(value, "<>&");
strtok
将返回您的value
指针,除了它会将字符串修改为:
"foo \0 bar & baz > frob"
您可能会注意到,它将 更改<
为NUL
. 但是,现在,如果你使用value
,你会得到,"foo "
因为NUL
中间有一个。
strtok
对with的后续调用NULL
将通过字符串进行,直到您到达字符串的末尾,此时您将获得NULL
.
char* str = "foo < bar & frob > nicate";
printf("%s\n", strtok(str, "<>&")); // prints "foo "
printf("%s\n", strtok(NULL, "<>&")); // prints " bar "
printf("%s\n", strtok(NULL, "<>&")); // prints " frob "
printf("%s\n", strtok(NULL, "<>&")); // prints " nicate"
assert(strtok(NULL, "<>&") == NULL); // should be true
编写一个strtok
无需.strpbrk
strcat