strtok和strtok_r源码解析

本文详细解析了C语言中的strtok和strtok_r函数,包括它们的源码实现。strtok用于按指定分隔符切割字符串,strtok_r是线程安全的版本。文章通过源码分析了如何处理分隔符、查找和结束标记,以及如何保存状态以便于下次调用。
摘要由CSDN通过智能技术生成

strtok源码简析

//官方的strtok函数,用来通过分隔字符(不支持字符串,传入的串中每个字符单独当分隔符,如下例子组合的如123会处理1而23会被跳过),返回分隔的串的首地址
//比如调用strtok("abc123def","123456");
//返回值是指向abc的指针
//下次要获得"def",需要调用strtok(NULL,"123456");函数用了一个类似全局变量的宏_TOKEN(想看实现的可以去查源码)来存储上次解析到的位置

/*
这里的方法比较巧,用一个32的byte数组当做索引表,其中的每一位表示ascii字符表中的255个字符(常用ascii和扩展ascii一共是256个,对应32个字节的256个位)是否存在,
用的是位移的方法,关键就是这句,map[*ctrl >> 3] |= (1 << (*ctrl & 7));
*ctrl >> 3:用字符的前5位来当索引,将256个字符分为32组
1 << (*ctrl & 7):这是1左移(*ctrl & 7)位,用后三位的值来当每一组的索引,表明自己是哪一位,比如:后三位是010=2,说明是第二位
|=:最后来个或操作,将那一位置为1,代表这一个ascii码有效
*/
/*
要判断字符是不是存在在索引中也就简单了,
map[*str >> 3] & (1 << (*str & 7))
值为1说明这个字符是存在的
*/

unsigned char map[32];
/* Clear control map */
for(count = 0; count < 32; count++)
        map[count] = 0;

/* Set bits in delimiter table */  // 设置分隔符位映射
do{
        map[*ctrl >> 3] |= (1<< (*ctrl & 7));
while(*ctrl++);

/* Initialize str */

/* If string is NULL, set str to the saved
* pointer (i.e., continue breaking tokens out of the string
* from the last strtok call) */

if(string)
        str = string;
else
        str = _TOKEN;

/* Find beginning of token (skip over leading delimiters). Note that
* there is no token iff this loop sets str to point to the terminal
* null (*str == '\0') */

while( (map[*str >> 3] & (1<< (*str & 7))) && *str )//去掉字符串前为非空分隔符的情况,没去掉为空分隔符的情况
        str++;

string = str;

/* Find the end of the token. If it is not the end of the string,
* put a null there. */

for( ; *str ; str++ )  // 找到分隔符,用空来代替
        if( map[*str >> 3] & (1<< (*str & 7)) ) {
                *str++ = '\0';

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值