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; 
} 
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

运行结果:
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; 
} 
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

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

猜你喜欢

转载自blog.csdn.net/wu694128/article/details/89712240