gpt4 book ai didi

c - 所以 strtok 是破坏性的?

转载 作者:行者123 更新时间:2023-12-04 11:44:51 26 4
gpt4 key购买 nike

我是否正确理解 strtok让源字符串充满空字符?

我可以理解,每个新的迭代调用首先用原始字符替换它放在那里的空字符,然后继续,最后一个调用返回 null,因为没有更多的游行,然后替换它最后放的最后一个空字符有它的原件。结果,源字符串最终不会被修改。 (当然,您是否会在最后一次调用之前停止,源字符串将保持修改状态。)

但是没有文件提到这种策略。因此,在使用 strtok 进行处理之前,我必须先将源字符串复制到另一个缓冲区。如果我希望源字符串保持不变?

最佳答案

C standard explicitly states 字符串 ... 分解成 ...”:

A sequence of calls to the strtok function breaks the string pointed to by s1 into a sequence of tokens


显式破坏“ s1 指向的字符串”不仅仅意味着原始字符串已被修改。
Note also the synopsis :
简介
     #include <string.h>
char *strtok(char * restrict s1,
const char * restrict s2);
它是 char * restrict s1 ,明显缺少任何 const .
请注意,“中断”字符串的是“调用序列”。在解析每个token后恢复字符串不符合“断字符串”的要求,或者在“调用序列”之后将字符串“断”。
POSIX makes the modification explicit (加粗我的):

The strtok() function then searches from there for a byte that is contained in the current separator string. If no such byte is found, the current token extends to the end of the string pointed to by s, and subsequent searches for a token shall return a null pointer. If such a byte is found, it is overwritten by a NUL character, which terminates the current token. The strtok() function saves a pointer to the following byte, from which the next search for a token shall start.

关于c - 所以 strtok 是破坏性的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60803240/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com