如何strtok()函数分割字符串成用C标记? [英] How does strtok() split the string into tokens in C?

查看:147
本文介绍了如何strtok()函数分割字符串成用C标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请给我解释一下的工作的strtok() function.The手册说它打破串入标记。我无法从实际上它做什么的说明书,了解。

我添加的手表上 STR * PCH 来检查它的工作,当第一while循环发生后, STR 的内容只有本。怎么印在屏幕上如下所示的输出?

  / * strtok的例子* /
#包括LT&;&stdio.h中GT;
#包括LT&;&string.h中GT;诠释的main()
{
  烧焦海峡[] = - 这,样本串;
  字符* PCH;
  的printf(分割字符串\\%s \\的成标记:\\ n,STR);
  PCH = strtok的(STR,.-);
  而(PCH!= NULL)
  {
    的printf(%S \\ n,PCH);
    PCH =的strtok(NULL,.-);
  }
  返回0;
}

输出:


分割字符串 - 这,样本串。成标记:
这个
一个
样品


解决方案

的strtok()把字符串为标记。即,从分隔符来下一个的任何一个开始将是你的一个标记。你的情况,起始标记将是 - 和旁边的空间,​​结束。那么下一个标记将从开始和结束,。在这里,你会得到这个作为输出。类似地,字符串的其余部分被分成标记从空间到空间,最后结束的最后一个标记。

Please explain me the working of strtok() function.The manual says it breaks the string into tokens. I am unable to understand from the manual what actually it does.

I added watches on str and *pch to check its working, when the first while loop occurred, the contents of str were only "this". How did the output shown below printed on the screen?

/* strtok example */
#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;
}

Output:

Splitting string "- This, a sample string." into tokens:
This
a
sample
string

解决方案

strtok() divides the string into tokens. i.e. starting from any one of the delimiter to next one would be your one token. In your case, the starting token will be from "-" and end with next space " ". Then next token will start from " " and end with ",". Here you get "This" as output. Similarly the rest of the string gets split into tokens from space to space and finally ending the last token on "."

这篇关于如何strtok()函数分割字符串成用C标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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