c - strtok 及其用法

标签 c string strtok

我正在做一项需要字符串和文件操作的作业。我目前正在研究字符串操作部分,并尝试使用 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/

相关文章:

c - 我如何将二维数组分配给其他临时二维数组.....?在 C 编程中

C-将矩阵传递给没有非常量列值的函数

c - 如何将特定大小的二维数组从动态更改为静态?

r - 在 R 中对齐打印字符串的标准工具是什么?

c - C++中复制字符串的函数选择,注重性能

c - 从字符串中提取整数并将其保存到链表中

C++ strtok - 多次使用更多数据缓冲区

c - 将具有未知数量元素的字符串扫描到 C 中的 int 数组

c - strtok 和 fgets 的奇怪数组行为

c - 一个 C 程序读取两个文件并在屏幕上显示它们的统计信息