如何使用strtok()

use*_*650 2 c printf token strtok

我正在编写一个C程序来研究strtok()用法的用法.这是我的代码:

#include <stdio.h>
#include <string.h>

main() {
    char abc[100] = "ls &";
    char *tok;

    tok = strtok(abc, " ");
    while (tok != NULL) {
        printf("%s", tok);
        tok = strtok(NULL, " ");
    }
    printf("\n\n\n\n\n%s", tok);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它打印以下输出:

ls&




(null)
Run Code Online (Sandbox Code Playgroud)

但我希望它在第二个printf语句中打印'&'.我该怎么做?我需要这部分作为我的作业项目.谁能帮我吗?

先感谢您!:)

Jon*_*ler 7

  1. 确保您可以识别打印时打印的限制.
  2. 在打印消息的末尾输出换行符; 如果你这样做,信息更有可能及时出现.
  3. 不要将NULL指针打印为字符串; 并非所有版本printf()都表现得很好 - 其中一些版本会转储核心.

码:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char abc[] = "ls &";
    char *tok;
    char *ptr = abc;

    while ((tok = strtok(ptr, " ")) != NULL)
    {
        printf("<<%s>>\n", tok);
        ptr = NULL;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

或者(优化,礼貌的自我.):

#include <stdio.h>
#include <string.h>

int main(void)
{
    char abc[] = "ls &";
    char *tok = abc;

    while ((tok = strtok(tok, " ")) != NULL)
    {
        printf("<<%s>>\n", tok);
        tok = NULL;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

<<ls>>
<<&>>
Run Code Online (Sandbox Code Playgroud)

您可以选择自己的标记字符,但是如果不弄乱XML或HTML,我会发现双角括号相当适合这项工作.

您也可以使用循环结构,但需要花费第二次调用strtok()(这是一个最小的成本,但可能会被认为违反了DRY原则:不要重复自己):

#include <stdio.h>
#include <string.h>

int main(void)
{
    char abc[] = "ls &";
    char *tok = strtok(abc, " ");

    while (tok != NULL)
    {
        printf("<<%s>>\n", tok);
        tok = strtok(NULL, " ");
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

相同的输出.


修订要求

我想printf()while循环外添加一个语句并在外面打印&.我需要它,因为我想稍后将它与程序中的另一个变量进行比较.有没有办法这样做?

是的,通常有办法做任何事情.这似乎有效.如果有更多的令牌要解析,或者只有&解析,或者没有令牌,它也能正常工作.显然,如果你愿意,可以将外环的主体制成一个功能; 这样做甚至是明智的.

#include <stdio.h>
#include <string.h>

int main(void)
{
    char tests[][16] =
    {
        "ls -l -s &",
        "ls &",
        "&",
        "    ",
        ""
    };

    for (size_t i = 0; i < sizeof(tests)/sizeof(tests[0]); i++)
    {
        printf("Initially: <<%s>>\n", tests[i]);
        char *tok1 = strtok(tests[i], " ");
        char *tok;

        while ((tok = strtok(NULL, " ")) != NULL)
        {
            printf("Loop body: <<%s>>\n", tok1);
            tok1 = tok;
        }
        if (tok1 != NULL)
            printf("Post loop: <<%s>>\n", tok1);
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Initially: <<ls -l -s &>>
Loop body: <<ls>>
Loop body: <<-l>>
Loop body: <<-s>>
Post loop: <<&>>
Initially: <<ls &>>
Loop body: <<ls>>
Post loop: <<&>>
Initially: <<&>>
Post loop: <<&>>
Initially: <<    >>
Initially: <<>>
Run Code Online (Sandbox Code Playgroud)

请注意标记在最后两个示例中如何为自己付出代价.如果没有标记,你无法区分它们.