对于由返回的字符串strtok
,它\0
的末尾是否有a?或者它不像strncpy
函数?
我会通过将 的返回值复制strtok
到另一个字符串数组来检查strcpy
,但是我不知道附加的是否是or\0
的效果(因为确实 add )。strtok
strcpy
strcpy
\0
编辑:对不起,我不能用“将返回值复制strtok
到另一个字符串数组strcpy
”。
记号的这一端会自动替换为空字符,并且记号的开头由函数返回。
从 C99 7.24.5.8
然后 strtok 函数从那里搜索包含在当前分隔符字符串中的字符。如果没有找到这样的字符,则当前标记延伸到 s1 所指向的字符串的末尾,随后搜索标记将返回一个空指针。如果找到这样的字符,它会被一个空字符覆盖,这会终止当前标记。strtok 函数保存指向下一个字符的指针,下一次搜索令牌将从该指针开始。
是的,最后返回的每个令牌strtok
都有'\0'
。它不仅仅是“包含”,它实际上被强制写入您的输入字符串。strtok
返回指向您的原始输入字符串的指针,并且它还会通过将这些指针写入其中来破坏您的输入字符串'\0'
。这是一个设计得很糟糕的功能,最好避免。
Yes there is a null terminator. It is at the delimiter last found. This is the reason that the first argument to strtok is not a const char *
: it modifies the buffer you gave it, meaning it cannot be const.
char buffer[0x20];
char *token;
sprintf(buffer, "Hello, world!");
printf("Address of BUFFER before strtok: %p\n", (void *)buffer);
token = strtok(buffer, ", !");
printf("Address of TOKEN after strtok: %p\n", (void *)token);
printf("Value of BUFFER: %s\n", buffer);
printf("Value of TOKEN: %s\n", token);
Run that, and you will understand that the first string passed is modified by strtok to change whatever delimiter after the first character was found first to a null terminator, meaning if you used ",,,Hello,,, world!", it would return "Hello\0,, world!".
After the first call to strtok, you can parse more tokens by passing NULL as the first argument to strtok. It will find the next non-delimiter token on its own. You can continue to do this until strtok returns NULL, in which case there are no more matches.
是的,确实如此。来自cplusplus
为了确定标记的开头和结尾,该函数首先从起始位置扫描不包含在分隔符中的第一个字符(它成为标记的开头)。然后从标记的开头开始扫描分隔符中包含的第一个字符,该字符成为标记的结尾。如果找到终止空字符,扫描也会停止。
我确实喜欢这样来检查 strtok 是否附加 '\0'
:
#include<stdio.h>
#include<string.h>
int main()
{
char str[]="here !is the! damn code";
setbuf(stdout,NULL);
char s[]="!";
char *token;
token=strtok(str,s);//first call: the function here expects str as argument and first scans from the starting location for the first character not contained in delimiters.
while(token!=NULL)
{
if(*token!='\0')
{
printf("the end of the token is replaced by a null character");// printed for each token which means that the delimiter was replaced by null character,and lastly at the end of the string.
printf("and the token is : %s\n",token);// tokens are printed
}
token=strtok(NULL,s);// the function expects a null pointer(NULL) and uses the position right after the end of last token as the new starting location for scanning in the subsequent calls.
}
return 0;
}
将分隔符的数量用于划分str
in标记,并将标记的结尾替换为空字符。因此,为每个标记打印语句,这意味着如果标记不会以空字符结尾,则语句将仅打印一次,即在结尾处。