在最近一个项目中,因为需要对一串解密后的字符串解析。发现原来的代码中用到了strtok函数,这个函数的作用是以固定的字符截取原字符串,分割成以固定字符为界限的多个字串。原型及使用方法如下:
(1)strtok原型:char *strtok(char s[], const char *delim);
头文件: "string.h"
(2)说明:
①当strtok()在参数s的字符串中发现参数delim中包含的分割字符时,则会将该字符改为\0 字符。在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL。每次调用成功则返回指向被分割出片段的指针。直到最后分割出的片段为NULL。
②返回值
从s开头开始的一个个被分割的串。当s中的字符查找到末尾时,返回NULL。如果查找不到delim中的字符时,返回当前strtok的字符串的指针。所有delim中包含的字符都会被滤掉,并将被滤掉的地方设为一处分割的节点。
③注意!!!使用该函数进行字符串分割时,会破坏源字符串的完整,调用前和调用后的s已经不一样了。第一次分割之后,原字符串str是分割完成之后的第一个字符串,剩余的字符串存储在一个静态变量中,因此多线程同时访问该静态变量时,则会出现错误。
(3)使用:
#include<string.h>
#include<stdio.h>
int main(void)
{
char input[16]="abc,d";
char*p;
/*strtok places a NULL terminator
infront of the token,if found*/
p=strtok(input,",");
if(p)
printf("%s\n",p);
/*Asecond 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\n",p);
return 0;
}
(4)安全函数
①strtok_s函数
strtok_s是windows下的一个分割字符串安全函数,其函数原型如下:
char *strtok_s( char *strToken, const char *strDelimit, char **buf);
这个函数将剩余的字符串存储在buf变量中,而不是静态变量中,从而保证了安全性。
②strtok_r函数
strtok_s函数是linux下分割字符串的安全函数,函数声明如下:
char *strtok_r(char *str, const char *delim, char **saveptr);
该函数也会破坏带分解字符串的完整性,但是其将剩余的字符串保存在saveptr变量中,保证了安全性。
使用:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[]="ab,cd,ef";
char *ptr;
char *p;
printf("before strtok: str=%s\n",str);
printf("begin:\n");
ptr = strtok_r(str, ",", &p);
while(ptr != NULL){
printf("str=%s\n",str);
printf("ptr=%s\n",ptr);
ptr = strtok_r(NULL, ",", &p);
}
return 0;
}
输出结果:
before strtok: str=ab,cd,ef begin: str=ab ptr=ab str=ab ptr=cd str=ab ptr=ef
(5)分割多个字符
strtok函数的分隔字符还可以是多个,不一定只为一个
p = strtok(buf, "$,");
这句代码的意思是以"$"和","为分隔符分割buf中的字符串。每当遇到这两个字符其中一个都会分割,不是遇到"$,"两个字符连在一起才分割,记住只需要遇到其中一个字符就可以了,这样对于函数的使用人性化很多。
再次提醒!!!使用这个函数会使源字符串改变,如果这个字符串是new出来的,那千万注意,因为改变后的字符串在delete时会出错!