当前位置: 首页 > 编程日记 > 正文

strtok和strtok_r

strtok和strtok_r

原型:char *strtok(char *s, char *delim);

功能:分解字符串为一组字符串。s为要分解的字符串,delim为分隔符字符串。

说明:首次调用时,s指向要分解的字符串,之后再次调用要把s设成NULL。
        strtok在s中查找包括在delim中的字符并用NULL('/0')来替换,直到找遍整个字符串。

返回值:从s开头開始的一个个被切割的串。当没有被切割的串时则返回NULL。
           全部delim中包括的字符都会被滤掉,并将被滤掉的地方设为一处切割的节点。

举例:

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


   
int main(void
)
{
       
char input[16] = "abc,d"
;
       
char *
p;

  
/*
strtok places a NULL terminator
        in front of the token, if found
*/

        p
= strtok(input, ","
);
       
if (p)      printf("%s "
, p);

   
/*
A second call to strtok using a NULL
        as the first parameter returns a pointer
        to the character following the token  
*/

        p
= strtok(NULL, ","
);
       
if (p)      printf("%s "
, p);

        return 0;
   }

      函数第一次调用需设置两个參数。第一次切割的结果,返回串中第一个 ',' 之前的字符串,也就是上面的程序第一次输出abc。

      第二次调用该函数strtok(NULL,"."),第一个參数设置为NULL。结果返回切割根据后面的字串,即第二次输出d。

带有_r的函数主要来自于UNIX以下。全部的带有_r和不带_r的函数的差别的是:带_r的函数是线程安全的,r的意思是reentrant,可重入的。

1. strtok介绍
众所周知,strtok能够依据用户所提供的切割符(同一时候分隔符也能够为复数比方“,。”)
将一段字符串切割直到遇到"/0".

比方,分隔符=“,” 字符串=“Fred,John,Ann”
通过strtok 就能够把3个字符串 “Fred”     “John”      “Ann”提取出来。
上面的C代码为

QUOTE:
int in=0;
char buffer[]="Fred,John,Ann"
char *p[3];
char *buf = buffer;
while((p[in]=strtok(buf,","))!=NULL) {
                 in++;
                 buf=NULL; }

如上代码,第一次运行strtok须要以目标字符串的地址为第一參数(buf=buffer),之后strtok须要以NULL为第一參数 (buf=NULL)。指针列p[],则储存了切割后的结果,p[0]="John",p[1]="John",p[2]="Ann",而buf就变成    Fred/0John/0Ann/0。

2. strtok的弱点
让我们更改一下我们的计划:我们有一段字符串 "Fred male 25,John male 62,Anna female 16" 我们希望把这个字符串整理输入到一个struct,

QUOTE:
struct person {
     char [25] name ;
     char [6] sex;
     char [4] age;
}

要做到这个,当中一个方法就是先提取一段被“,”切割的字符串,然后再将其以“ ”(空格)切割。
比方: 截取 "Fred male 25" 然后切割成 "Fred" "male" "25"
下面我写了个小程序去表现这个过程:

QUOTE:
#include<stdio.h>
#include<string.h>
#define INFO_MAX_SZ 255
int main()
{
   int in=0;
   char buffer[INFO_MAX_SZ]="Fred male 25,John male 62,Anna female 16";
   char *p[20];
   char *buf=buffer;

   while((p[in]=strtok(buf,","))!=NULL) {
             buf=p[in];
             while((p[in]=strtok(buf," "))!=NULL) {
                       in++;
                       buf=NULL;
                    }
                 p[in++]="***"; //表现切割
                 buf=NULL; }

   printf("Here we have %d strings/n",i);
   for (int j=0; j<in; j++)
         printf(">%s</n",p[j]);
   return 0;
}

这个程序输出为:
Here we have 4 strings
>Fred<
>male<
>25<
>***<
这仅仅是一小段的数据,并非我们须要的。但这是为什么呢? 这是由于strtok使用一个static(静态)指针来操作数据,让我来分析一下以上代码的执行过程:

红色为strtok的内置指针指向的位置蓝色为strtok对字符串的改动

1. "Fred male 25,John male 62,Anna female 16" //外循环

2. "Fred male 25/0John male 62,Anna female 16" //进入内循环

3.    "Fred/0male 25/0John male 62,Anna female 16"

4.    "Fred/0male/025/0John male 62,Anna female 16"

5 "Fred/0male/025/0John male 62,Anna female 16" //内循环遇到"/0"回到外循环

6   "Fred/0male/025/0John male 62,Anna female 16" //外循环遇到"/0"执行结束。

3. 使用strtok_r
在这样的情况我们应该使用strtok_r, strtok reentrant.
char *strtok_r(char *s, const char *delim, char **ptrptr);

相对strtok我们须要为strtok提供一个指针来操作,而不是像strtok使用配套的指针。
代码:

QUOTE:
#include<stdio.h>
#include<string.h>
#define INFO_MAX_SZ 255
int main()
{
   int in=0;
   char buffer[INFO_MAX_SZ]="Fred male 25,John male 62,Anna female 16";
   char *p[20];
   char *buf=buffer;

   char *outer_ptr=NULL;
   char *inner_ptr=NULL;

   while((p[in]=strtok_r(buf,",",&outer_ptr))!=NULL) {
             buf=p[in];
             while((p[in]=strtok_r(buf," ",&inner_ptr))!=NULL) {
                       in++;
                       buf=NULL;
                    }
                 p[in++]="***";
                 buf=NULL; }

   printf("Here we have %d strings/n",i);
   for (int j=0; jn<i; j++)
         printf(">%s</n",p[j]);
   return 0;
}

这一次的输出为:
Here we have 12 strings
>Fred<
>male<
>25<
>***<
>John<
>male<
>62<
>***<
>Anna<
>female<
>16<
>***<


让我来分析一下以上代码的执行过程:

红色为strtok_r的outer_ptr指向的位置
紫色为strtok_r的inner_ptr指向的位置
蓝色为strtok对字符串的改动

1. "Fred male 25,John male 62,Anna female 16" //外循环

2. "Fred male 25/0John male 62,Anna female 16"//进入内循环

3.   "Fred/0male 25/0John male 62,Anna female 16"

4   "Fred/0male/025/0John male 62,Anna female 16"

5 "Fred/0male/025/0John male 62,Anna female 16" //内循环遇到"/0"回到外循环

6   "Fred/0male/025/0John male 62/0Anna female 16"//进入内循环

转载于:https://www.cnblogs.com/bhlsheji/p/4084022.html

相关文章:

iOS 标签自动布局

导入SKTagFrame SKTagFrame *frame [[SKTagFrame alloc] init];frame.tagsArray self.bigModel.Tags;// 添加标签CGFloat first_H 0;CGFloat total_H 0;for (NSInteger i 0; i< self.bigModel.Tags.count; i) {UIButton *tagsBtn [UIButton buttonWithType:UIButtonT…

引导分区 pbr 数据分析_如何在1小时内引导您的分析

引导分区 pbr 数据分析by Tim Abraham蒂姆亚伯拉罕(Tim Abraham) 如何在1小时内引导您的分析 (How to bootstrap your analytics in 1 hour) Even though most startups understand how critical data is to their success, they tend to shy away from analytics — especial…

SSL 1460——最小代价问题

Description 设有一个nm(小于100)的方格&#xff08;如图所示&#xff09;&#xff0c;在方格中去掉某些点&#xff0c;方格中的数字代表距离&#xff08;为小于100的数&#xff0c;如果为0表示去掉的点&#xff09;&#xff0c;试找出一条从A(左上角)到B&#xff08;右下角&am…

在Windows 7下面IIS7的安装和 配置ASP的正确方法

在Windows 7下如何安装IIS7&#xff0c;以及IIS7在安装过程中的一些需要注意的设置&#xff0c;以及在IIS7下配置ASP的正确方法。 一、进入Windows 7的 控制面板&#xff0c;选择左侧的打开或关闭Windows功能 。二、打开后可以看到Windows功能的界面&#xff0c;注意选择的项目…

适配iOS 13 tabbar 标题字体不显示以及返回变蓝色的为问题

// 适配iOS 13 tabbar 标题字体不显示以及返回变蓝色的为问题 if (available(iOS 13.0, *)) {//[[UITabBar appearance] setUnselectedItemTintColor:Color_666666];}

企业不要求工程师资格认证_谁说工程师不能成为企业家?

企业不要求工程师资格认证by Preethi Kasireddy通过Preethi Kasireddy 谁说工程师不能成为企业家&#xff1f; (Who says engineers can’t become entrepreneurs?) A lot of people warned me not to walk away from my great position at Andreessen Horowitz to pursue so…

BestCoder Round #92 比赛记录

上午考完试后看到了晚上的BestCoder比赛,全机房都来参加 感觉压力好大啊QAQ,要被虐了. 7:00 比赛开始了,迅速点进了T1 大呼这好水啊!告诉了同桌怎么看中文题面 然后就开始码码码,4分16秒AC了第一题 7:05 开始看第二题 诶诶诶!!~~~~直接爆搜不久能过吗? 交了一发爆搜上去,AC了,…

[cocos2dx UI] CCLabelAtlas 为什么不显示最后一个字

CClabelAtlas优点&#xff0c;基本用法等我就不说了&#xff0c;这里说一个和美术配合时的一个坑&#xff01;就是图片的最后一位怎么也不显示&#xff0c;如下图中的冒号不会显示 查了ASCII码表&#xff0c;这个冒号的值为58&#xff0c;就是在9&#xff08;57&#xff09;的后…

iOS 13 适配TextField 崩溃问题

iOS 13 之后直接通过以下方式修改Textfield的时候会出现报错信息 [_accountText setValue:Color_666666 forKeyPath:"_placeholderLabel.textColor"]; 报错信息 Access to UITextField’s _placeholderLabel ivar is prohibited. This is an application bug 解决…

测试django_如何像专业人士一样测试Django Signals

测试djangoby Haki Benita通过Haki Benita 如何像专业人士一样测试Django Signals (How to test Django Signals like a pro) For a better reading experience, check out this article on my website.为了获得更好的阅读体验&#xff0c;请在我的网站上查看此文章 。 Djang…

C#中静态方法的运用和字符串的常用方法(seventh day)

又来到了今天的总结时间&#xff0c;由于昨天在云和学院学的知识没有弄懂&#xff0c;今天老师又专门给我们非常详细地讲了一遍&#xff0c;在这里非常谢谢老师。O(∩_∩)O 话不多说&#xff0c;下面就开始为大家总结一下静态方法的运用和字符串的常用方法。 理论&#xff1a;静…

raid 磁盘阵列

mkdir /uuu #建挂载目录echo "- - -" > /sys/class/scsi_host/host2/scan #扫描新硬盘 lsblk #查看 parted /dev/sdb #分区 parted /dev/sdc lsblk mdadm -Cv /dev/md1 -l1 -n2 -c128 /dev/sd[b,c]1 #raid1配置&#xff0c; /dev/md1名字&#…

iOS 13 如何删除SceneDelegate

Xcode11之后新创建的工程会多出两个文件SceneDelegate。那么我们如何让它变回之前的那样的工程呢。 一、将这两个文件删除。 会报错There is no scene delegate set. A scene delegate class must be specified to use a main storyboard file. 二、将Info.plist 中的 SceneMai…

女性程序员大会ghc_在女性科技大会上成为男人的感觉

女性程序员大会ghcby Elijah Valenciano通过伊莱贾瓦伦西亚诺 在女性科技大会上成为男人的感觉 (What It’s Like to be a Man at a Women’s Tech Conference) To be honest, I was very nervous. A few panicked thoughts started to flood my mind as I prepared myself to…

cf776G.Sherlock and the Encrypted Data

题意:对于一个16进制数x,把x的各个数位拿出来,设其为t1,t2,...,定义s(x)为2^t1|2^t2|...,如x0x3e53,则s(x)2^3|2^14|2^5|2^316424.给出q组询问l,r(l,r也是16进制数,不超过15位),求[l,r]中有多少个数x满足x^s(x)<x. 这题题解写的是个状压数位dp,但是蒟蒻不会数位dp,自己YY了一…

c++, 派生类的构造函数和析构函数 , [ 以及operator=不能被继承 or Not的探讨]

说明&#xff1a;文章中关于operator实现的示例&#xff0c;从语法上是对的&#xff0c;但逻辑和习惯上都是错误的。 参见另一篇专门探究operator的文章&#xff1a;《c&#xff0c;operator》http://www.cnblogs.com/mylinux/p/4113266.html 1.构造函数与析构函数不会被继承&a…

json转换模型利器--JSONExport

JSONExport 从json 到 Model &#xff0c;如此的方便 swift oc java 全部支持

亚马逊ses如何发qq_使用Amazon SES发送电子邮件

亚马逊ses如何发qqby Kangze Huang黄康泽 使用Amazon SES发送电子邮件 (Sending emails with Amazon SES) 完整的AWS Web样板-教程3 (The Complete AWS Web Boilerplate — Tutorial 3) 目录 (Table of Contents) Part 0: Introduction to the Complete AWS Web Boilerplate第…

源码-0205-02--聊天布局

还真是失败&#xff0c;搞了两天遇到了布局cell高度总是出差的问题&#xff0c;cell height不是高很多很多&#xff0c;就是就是矮到没有的情况。。。。糟糕透顶待解救&#xff5e; 聊天布局 // // XMGChatingViewController.m // 07-聊天布局 #import "XMGChatingViewC…

js实现页面跳转的几种方式

第一种&#xff1a;<script language"javascript" type"text/javascript"> window.location.href"login.jsp?backurl"window.location.href; </script>第二种&#xff1a; <script language"javascript&q…

Mac 升级系统 pod 命令无效

mac 升级完最新的系统之后 使用pod 命令之后无效报错 -bash: /usr/local/bin/pod: /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/bin/ruby: bad interpreter: No such file or directory 解决方案 sudo gem install -n /usr/local/bin cocoapods

node seneca_使用Node.js和Seneca编写国际象棋微服务,第1部分

node seneca(This is Part 1 of a three-part series [Part 2, Part 3])(这是一个由三部分组成的系列文章的第1部分[ 第2 部分 &#xff0c; 第3部分 ]) I’ve begun wrapping my head around microservices. Up to this time I regarded it as a scalability pattern and ove…

Ubuntu中基于QT的系统网线连接状态的实时监视

1.必要准备 需包&#xff1a; #include <QNetworkInterface> 2.实现获取当前的网线连接状态 以下是自己在网络上搜到的一个解决方法&#xff0c;且没有加入iface.flags().testFlag(QNetworkInterface::IsRunning) 这一逻辑判断&#xff0c;经测试实时性极不可靠&#xff…

iOS 开发者账号 到期续费问题

https://blog.csdn.net/liruiqing520/article/details/104043221

[转载]Using ngOptions In AngularJS

http://odetocode.com/blogs/scott/archive/2013/06/19/using-ngoptions-in-angularjs.aspx?utm_sourcetuicool转载于:https://www.cnblogs.com/Benoly/p/4097213.html

graphql_GraphQL的稳步上升

graphqlToday GitHub announced that the next version of their API will use a new technology developed by Facebook called GraphQL.今天&#xff0c;GitHub宣布其API的下一版本将使用Facebook开发的一项名为GraphQL的新技术。 GraphQL may eventually come to replace t…

转: windows系统下mysql出现Error 1045(28000) Access Denied for user 'root'@'localhost'

windows系统下mysql出现Error 1045(28000) Access Denied for user rootlocalhost 转自 http://zxy5241.spaces.live.com/blog/cns!7682A3008CFA2BB0!361.entry 在windows操作系统安装MySQL数据库&#xff0c;碰到Error 1045(28000) Access Denied for user rootlocalhost 错误…

正则表达式的字符、说明和其简单应用示例

字符和其含义 字符       含义 \         转义字符&#xff0c;将一个具有特殊功能的字符转义为一个普通的字符 ^        匹配字符串的开始位置 $        匹配字符串的结束位置 *        匹配前面的0次或多次的子表达式        …

iOS 设置UILabel 的行间距

// // UILabelLineSpace.h//#import <UIKit/UIKit.h>NS_ASSUME_NONNULL_BEGINinterface UILabel (LineSpace)/**设置文本,并指定行间距param text 文本内容param lineSpacing 行间距*/ -(void)setText:(NSString*)text lineSpacing:(CGFloat)lineSpacing;endNS_ASSUME_N…

倦怠和枯燥_启动倦怠

倦怠和枯燥by Elie Steinbock埃莉斯坦博克(Elie Steinbock) 启动倦怠 (Start-up Burnout) Shabbat is the seventh day of the week. It starts on Friday night and ends on the following evening, Saturday. (A day starts in the evening for the Jews.) It’s also the J…