strtok 函数解析 及缺陷

2023-05-16

strtok:
#include <string.h>
char *strtok(char *str, const char *delim);
char *strtok_r(char *str, const char *delim, char **saveptr);
功能:分解字符串为一组标记串。str为要分解的字符串,delim为分隔符字符串。
说明:首次调用时,str必须指向要分解的字符串,随后调用要把s设成NULL。
      strtok在str中查找包含在delim中的字符并用NULL('/0')来替换,直到找遍整个字符串。
      返回指向下一个标记串。当没有标记串时则返回空字符NULL。
实例:用strtok来判断ip地址是否合法:ip_strtok.c:

/* strtok example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="- This, , a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}

输出

Splitting string "- This, , a sample string." into tokens:
This
a
sample
string


 

一个自己实现的strtok 函数

char *xl_strtok(char *s, const char *dm)
{
    static char *last;
    char *tok=NULL;
    if(s == NULL)
        s = last;
    if(*s == '\0')
        return NULL;
    while (*s != '\0'){
        int i=0;
        last = s + 1;
        while (dm[i]){
            if (*s == dm[i++]){
                *s = '\0';
                if(tok!=NULL)return tok;
                break;
            }
        }
        if(*s!='\0'&&tok==NULL){
            tok=s;
        }
        ++s;
    }
    return tok;
}


 


 缺陷

int main ()
{
    char test1[] = "feng,ke,wei";
    char *test2 = "feng,ke,wei";
    char str[] ="- This, , a sample string.";
    char * pch;
    printf ("Splitting string \"%s\" into tokens:\n",str);
    pch = xl_strtok (test2," ,.-");
    while (pch != NULL)
    {
        printf ("%s\n",pch);
        pch = xl_strtok (NULL, " ,.-");
    }
    return 0;
}


测试代码中test1 和str 都可以正常运行,但是test2时就出现内存错误。其原因主要是test2不允许被修改。



 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

strtok 函数解析 及缺陷 的相关文章

随机推荐