strtok.c

来自「几个C++库函数,也是经常用来测试编程实力的函数!」· C语言 代码 · 共 38 行

C
38
字号
///////    Separate tokens in a string    /////// 
#include <iostream>
#include <string.h>
typedef char *CString;

CString strtok(CString s, const char *cs)
{ CString token;
  static CString spt; // starting pointer 
      if( s != NULL ) spt = s;
      if( *spt == '\0' ) return(NULL);
      // locate beginning of token 
      while( *spt != '\0' && strchr(cs, *spt) != NULL ) spt++;
      token = spt;
      // locate end of token 
      while( *spt != '\0' && strchr(cs, *spt) == NULL ) spt++;
      *spt = '\0' ;
      spt++;
      return(token);
}

#define WHITE "\t \n\r"

#ifdef TEST
int main()
{    char st1[] = "There it is.";
     char st2[] = "\n \t A string\n \r  of 1 or more   \t tokens";
     CString tk = strtok(st1, WHITE);
     do { std::cout << tk << std::endl;
     } while ( (tk = strtok(NULL, WHITE)) != NULL);

     tk = strtok(st2, WHITE);
     do { std::cout << tk << std::endl;
     } while ( (tk = strtok(NULL, WHITE)) != NULL);
     return 0;
}
#endif

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?