我正在做一项需要字符串和文件操作的作业。我目前正在研究字符串操作部分,并尝试使用 strtok 来分隔文件中的行,并用逗号分隔。但是,我不确定 strtok 是如何工作的。我正在查看下面的代码,不太明白为什么第二个 strtok 调用中有 NULL,而 NULL 甚至不是字符串。
我正在运行的代码:
/**************************************************** ****************** * * 目的:演示“strtok”功能的程序。 * 作者:M·J·莱斯利 * 日期:94 年 4 月 23 日 * ****************************************************** **************/
#include <stdio.h>
#include <string.h>
main()
{
/* Copy the constant into the memory
* pinted to by 'test_string' */
char test_string[50]="string to split up";
/* if 'test_string' is declared as below and the program will give a
* 'Segmentation fault' This is because test_string' is pointing
* to a constant i.e. somethin that cant be changed.
char *test_string="string to split up"; */
char *sub_string;
/* Extract first string */
printf("%s\n", strtok(test_string, " "));
/* Extract remaining
* strings */
while ( (sub_string=strtok(NULL, " ")) != NULL)
{
printf("%s\n", sub_string);
}
}
/*****************************************************************
*
* Program O/P will look like this...
*
* string
* to
* split
* up
*
*****************************************************************/
最佳答案
来自documentation :
Each subsequent call, with a null pointer as the value of the first argument, starts searching from the saved pointer and behaves as described above.
关于c - strtok 及其用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47685239/