如何在C的strtok函数工作? [英] How does the strtok function in C work?

查看:136
本文介绍了如何在C的strtok函数工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这解释了 strtok的功能本示例程序:

I found this sample program which explains the strtok function:

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

int main ()
{
    char str[] ="- This, a sample string.";
    char * pch;
    printf ("Splitting string \"%s\" into tokens:\n",str);
    pch = strtok (str," ,.-");
    while (pch != NULL)
    {
        printf ("%s\n",pch);
        pch = strtok (NULL, " ,.-");
    }
    return 0;
}

不过,我不明白这是怎么可能的工作。

However, I don't see how this is possible to work.

这怎么可能, PCH =的strtok(NULL,.-); 返回一个新令牌。我的意思是,我们呼吁 strtok的 NULL 。这doesen't做了很多有意义的我。

How is it possible that pch = strtok (NULL, " ,.-"); returns a new token. I mean, we are calling strtokwith NULL . This doesen't make a lot sense to me.

推荐答案

两件事情了解 strtok的。正如所提到的,保持内部状态。此外,它的弄乱你给它的字符串。从本质上讲,它会写'\\ 0'在这里找到您所提供的令牌,并返回一个指向字符串的开始。在内部它保持了最后一个令牌的位置;和明年你怎么称呼它的时候,它开始从那里。

Two things to know about strtok. As was mentioned, it "maintains internal state". Also, it messes up the string you feed it. Essentially, it will write a '\0' where it finds the token you supplied, and returns a pointer to the start of the string. Internally it maintains the location of the last token; and next time you call it, it starts from there.

重要的推论是,你不能使用 strtok的为const char *的Hello World; 键入字符串,因为当您修改为const char * 字符串的内容将得到一个访问冲突。

The important corollary is that you cannot use strtok on a const char* "hello world"; type of string, since you will get an access violation when you modify contents of a const char* string.

关于 strtok的好的事情是,它实际上并没有复制字符串 - 这样你就不会需要管理更多内存分配等,但除非你明白上面,你会正确使用它有麻烦了。

The "good" thing about strtok is that it doesn't actually copy strings - so you don't need to manage additional memory allocation etc. But unless you understand the above, you will have trouble using it correctly.

例子 - 如果你有这是一个,字符串,连续调用 strtok的将产生指针如下( ^ 是返回的值)。请注意,'\\ 0'这个标记是发现添加;这意味着源字符串修改:

Example - if you have "this,is,a,string", successive calls to strtok will generate pointers as follows (the ^ is the value returned). Note that the '\0' is added where the tokens are found; this means the source string is modified:

t  h  i  s  ,  i  s  ,  a  ,  s  t  r  i  n  g \0         this,is,a,string

t  h  i  s  \0 i  s  ,  a  ,  s  t  r  i  n  g \0         this
^
t  h  i  s  \0 i  s  \0 a  ,  s  t  r  i  n  g \0         is
               ^
t  h  i  s  \0 i  s  \0 a  \0 s  t  r  i  n  g \0         a
                        ^
t  h  i  s  \0 i  s  \0 a  \0 s  t  r  i  n  g \0         string
                              ^

希望这是有道理的。

Hope it makes sense.

这篇关于如何在C的strtok函数工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆