strtok() 如何将字符串拆分为 C 中的标记? [英] How does strtok() split the string into tokens in C?

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

问题描述

请向我解释 strtok() 函数的工作原理.该手册说它将字符串分解为标记.我无法从手册中了解它的实际作用.

我在 str*pch 上添加了 watch 来检查它在第一个 while 循环发生时的工作,str 的内容只有这个".下面显示的输出是如何打印在屏幕上的?

/* strtok 示例 */#include #include int主(){char str[] ="- 这是一个示例字符串.";字符 * pch;printf("将字符串"%s"拆分为标记:
",str);pch = strtok(str,",.-");而 (pch != NULL){printf ("%s
",pch);pch = strtok (NULL, ",.-");}返回0;}

输出:

<前>拆分字符串- this,一个示例字符串."成令牌:这个一种样本细绳

解决方案

strtok() 将字符串分成标记.即从任何一个分隔符开始到下一个分隔符将是您的一个标记.在您的情况下,起始标记将来自-"并以下一个空格"结束.然后下一个标记将从"开始并以,"结束.在这里,您将获得This"作为输出.类似地,字符串的其余部分从一个空格到另一个空格拆分为标记,最后以."结束最后一个标记.

Please explain to me the working of strtok() function. The manual says it breaks the string into tokens. I am unable to understand from the manual what it actually 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:
",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s
",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天全站免登陆