【问题标题】:strtok and it's usagestrtok 及其用法
【发布时间】:2017-12-06 23:32:09
【问题描述】:

我正在处理需要字符串和文件操作的作业。我目前正在处理字符串操作部分,我正在尝试使用 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
 *
 *****************************************************************/

【问题讨论】:

  • 有什么问题?只需阅读函数说明即可。
  • strtokNULL 将从上次调用它的位置继续
  • 公平地说,strtok() 是可憎的,而且非常愚蠢。

标签: c string strtok


【解决方案1】:

来自documentation

随后的每个调用都以空指针作为第一个参数的值,从保存的指针开始搜索并按照上述方式进行操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-01
    • 2018-07-16
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多