strtok()函数的实现

小结字符串处理函数:
1.注意字符串的特征,末尾’\0’
2.遍历是最常见的,如果一个字符串中查询另一个
一定要分清谁在前后的问题

strtok函数对于字符串的切割,很好用的。
分解字符串为一组字符串。s为要分解的字符,delim为分隔符字符(如果传入字符串,则传入的字符串中每个字符均为分割符)。首次调用时,s指向要分解的字符串,之后再次调用要把s设成NULL。

作用于字符串s,以包含在delim中的字符为分界符,将s切分成一个个子串;如果,s为空值NULL,则函数保存的指针SAVE_PTR在下一次调用中将作为起始位置。

下面对于对于它的使用,进行举例:

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

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

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


   p = strtok(NULL, ","); 
   printf("%s\n", p); 
   return 0; 
} 

运行结果:
abc
d
Press any key to continue

下面自己实现一个my_strtok()函数

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


char * my_strtok(char *str,char *demion);

char *my_strtok(char *str,char *demion)
{
    static char *p_last = NULL;
    if(str == NULL && (str = p_last) == NULL)
    {
        return NULL;
    }   


      char *s = str;
      char *t= NULL;
      while(*s != '\0')
      {
          t= demion;
          while(*t != '\0')
          {
              if(*s == *t)
              {
                  p_last  = s +1;
                  if( s - str == NULL)
                  {
                      str = p_last;
                      break;
                  }
                  *s = '\0';
                  return str;
              }


              t++;
          }
          s++;
      }
      return NULL;
}
int main(void) 
{ 
  char str[] = "liusen,lin,lll";
  char * result = NULL;
  result = my_strtok(str,",");
  printf("%s\n",result);
  result = my_strtok(NULL,",");
  printf("%s\n",result);
   return 0; 
} 

运行结果:
liusen
lin
Press any key to continue

  • 7
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值