字符串分割利器—strtok_r函数

来源:互联网 发布:mac os sierra 编辑:程序博客网 时间:2024/06/04 22:41


最近工作需要用到了strtok_r函数,他的主要作用是按某个字符来分割字符串。

比如按空格分割 字符串 “You are crazy”,依次得到的结果是"You" , "are" , "crazy",


函数原型:

      #include <string.h>

       char *strtok_r(char *str, const char *delim, char **saveptr);


函数的返回值是  排在前面的   被分割出的字串,或者为NULL,

str是传入的字符串。需要注意的是  :第一次使用strtok_r之后,要把str置为NULL,

delim指向依据分割的字符串。常见的空格“ ”    逗号“,”等

saveptr保存剩下待分割的字符串。


比如:按空格分割 字符串 “You are crazy”,

分第一次得字串"You",然后saveptr指向了"are crazy"

分第2次得字串"are",然后saveptr指向了"crazy"

分第3次得字串"crazy",然后saveptr指向了NULL

结束。


另外值得注意的是str不能指向常量指针,不然出现程序崩溃。


上代码:

#include <stdio.h>  #include <time.h>  #include <stdlib.h>  #include <string.h>  #include <unistd.h>void func(){char *pchSrc = "Can I help you";char chBuffer[102] ;char *pchDilem = " ";char *pchStrTmpIn = NULL;char *pchTmp = NULL;strncpy(chBuffer,pchSrc ,sizeof(chBuffer) - 1);pchTmp = chBuffer;while(NULL != ( pchTmp = strtok_r( pchTmp, pchDilem, &pchStrTmpIn) )){printf("\n pchTmp[%s] pchStrTmpIn[%s]\n",pchTmp,pchStrTmpIn);//printf("\n pchTmp[%s] \n",pchTmp);pchTmp = NULL;}}int main(){func();return 0;}


 gcc test.c -g