日期:2014-05-16  浏览次数:20813 次

关于LINUX C中函数strtok使用要点

strtok函数的使用是一个老生常谈的问题了。该函数的作用很大,争议也很大。以下的表述

使用的源代码大部分来自于网络,我稍加修改作为例证。当然,本人水平有限,有不妥之处望各位多多指教。

strtok的函数原型为char *strtok(char *s, char *delim),功能为“Parse S into tokens separated by characters in DELIM.If S is NULL, the saved pointer in SAVE_PTR is used as the next starting point. ” 翻译成汉语就是:作用于字符串s,以包含在delim中的字符为分界符,将s切分成一个个子串;如果,s为空值NULL,则函数保存的指针SAVE_PTR在下一次调用中将作为起始位置。

函数的返回值为从指向被分割的子串的指针。

要点纪要:

1.函数的作用是分解字符串,所谓分解,即没有生成新串,只是在str所指向的内容上做了些手脚而已。因此,源字符串str发生了变化!

下面就以str[] = "ab,c,d"为简单案例一代吗来证实其str发生了变化:


?

点击(此处)折叠或打开

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

  3. int main(void)
  4. {
  5. ??char str[] = "ab,c,d";
  6. ??char *p = NULL;
  7. ??char delim = ",";

  8. ??int in = 0;
  9. ??p = strtok(str, delim);
  10. ??while(p != NULL){
  11. ????printf("the character is :%s\n",p);
  12. ????printf("the str is : %s\n",str);
  13. ????p = strtok(NULL,delim