strtok及其在字符串分析中的应用

来源:互联网 发布:app数据录入 编辑:程序博客网 时间:2024/06/11 09:59

原型:extern char *strtok(char *s, char *delim);

用法:#include <string.h>

功能:分解字符串为一组标记串。s为要分解的字符串,delim为分隔符字符串。

说明:首次调用时,s必须指向要分解的字符串,随后调用要把s设成NULL。

            strtok在s中查找包含在delim中的字符并用NULL('\0')来替换,直到找遍整个字符串。

            返回指向下一个标记串。但没有标记串时则返回空字符NULL。


例子:

      // strtok.c            #include <syslib.h>      #include <string.h>      #include <stdio.h>      main()      {        char *s="Golden Global View";        char *d=" ";char *p;                clrscr();                p=strtok(s,d);        while(p)        {          printf("%s\n",s);          strtok(NULL,d);        }        getchar();        return 0;      }


字符串分析:

/* Code supplied by Prelude */#include <stdio.h> #include <string.h> #define DELIM   " " #define MAXWORD 80 #define MAXLEN  20 int main(void){  char  words[MAXWORD][MAXLEN];  char  buff[BUFSIZ];  int   ntokens = 0;  int   i;  printf("Enter a string: ");  fflush(stdout);  if (fgets(buff, sizeof buff, stdin) != NULL)  {    char  *sep = strtok(buff, DELIM);    while (sep != NULL)    {      strcpy(words[ntokens++], sep);      sep = strtok(NULL, DELIM);    }  }  for (i = 0; i < ntokens; i++)   {    puts(words[i]);  }  return(0);}/* * Output :  Enter a string: this is a long line of text  this  is  a  long  line  of  text * */



原创粉丝点击