C语言 如何使用 strtok()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18927793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:30:20  来源:igfitidea点击:

How to use strtok()

cprintftokenstrtok

提问by user2201650

I'm writing a C program to study the usage of function strtok(). Here is my code:

我正在编写一个 C 程序来研究 function 的用法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;
}

It is printing the following output:

它正在打印以下输出:

ls&




(null)

But I want it to print &at the second printfstatement. How do I do it? I need this part for my homework project.

但我希望它&在第二个printf语句中打印。我该怎么做?我的家庭作业项目需要这部分。

回答by Jonathan Leffler

  1. Make sure you can identify the limits of what you print when you're printing.
  2. Output newlines at the end of printed messages; the information is more likely to appear in a timely manner if you do that.
  3. Don't print NULL pointers as strings; not all versions of printf()will behave nicely — some of them dump core.
  1. 确保您可以在打印时确定打印内容的限制。
  2. 在打印消息的末尾输出换行符;如果您这样做,信息更有可能及时出现。
  3. 不要将 NULL 指针打印为字符串;并非所有版本printf()都表现良好——其中一些会转储核心。

Code:

代码:

#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;
}

Or (optimized, courtesy of self.):

或(优化,自我礼貌):

#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;
}

Output:

输出:

<<ls>>
<<&>>

You can choose your own marker characters, but when not messing with XML or HTML, I find the double angle brackets reasonably good for the job.

您可以选择自己的标记字符,但是当不使用 XML 或 HTML 时,我发现双尖括号非常适合这项工作。

You can also use your loop structure at the cost of writing a second call to strtok()(which is a minimal cost, but might be argued to violate the DRY principle: Don't Repeat Yourself):

您还可以以编写第二次调用为代价来使用循环结构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;
}

Same output.

相同的输出。



Revised requirement

修订要求

I would like to add a printf()statement outside the whileloop and print '&' outside. I need it since I want to compare it later with another variable in the program. Is there any way to do so?

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

Yes, there is usually a way to do almost anything. This seems to work. It also works sanely if there are more tokens to parse, or if there's only the &to parse, or if there are no tokens. Clearly, the body of the outer loop could be made into a function if you so wished; it would be sensible to do so, even.

是的,通常有一种方法可以做几乎任何事情。这似乎有效。如果要解析的标记更多,或者只有&要解析的标记,或者没有标记,它也可以正常工作。显然,如果您愿意,可以将外循环的主体变成一个函数;这样做是明智的,甚至。

#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;
}

Output:

输出:

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: <<>>

Note how the markers pay for themselves in the last two examples. You couldn't tell those apart without the markers.

请注意在最后两个示例中标记如何为自己付费。没有标记,你无法区分这些。

回答by all0star

you should write sth like this:

你应该这样写:

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

int main();
{
char string[] = "ls &"; //you should not write 100, cuz you waste memory
char *pointer;

pointer = strtok(string, " "); //skip only spaces
while(pointer != NULL)
   {
      printf("%s\n", pointer);
      pointer = strtok(string, " ");
   }
return 0;
}