Does strtok work with strings (as the delimiter)? [closed]

℡╲_俬逩灬. 提交于 2019-11-26 23:44:07

问题


For example:

Friendly.

I don't like the "ly" at the end of the word. Can I tokenize this string by "ly"

someCharVariable = strtok("friendly", "ly")?


回答1:


The answer is no. Your example of "ly" will delimit on any occurrence of either "l" or "y" or "yl" or "ly"

The delimiter parameter is an array of characters, each meant to act as a delimiter.

This is an example of what you asked for:

char *iterate(char *p, const char *d, const size_t len)
{   
   while(p!=NULL && *p && memcmp(p, d, len)==0)
   {
      memset(p, 0x0, len);
      p+=len;    
   }
   return p;
}

char **
tokenize( char **result, char *working, const char *src, const char *delim)
{
     int i=0;
     char *p=NULL;
     size_t len=strlen(delim);     
     strcpy(working, src);
     p=working;
     for(result[i]=NULL, p=iterate(p, delim, len); p!=NULL && *p; p=iterate(p, delim, len) )
     {
         result[i++]=p;
         result[i]=NULL;
         p=strstr(p, delim);
     }
     return result;
}



回答2:


strtok returns char *. so u need to use somechar*var not somecharvariable.

your code will return the pointer to string "friend" and "l" will be replaced by '/0'.



来源:https://stackoverflow.com/questions/14867213/does-strtok-work-with-strings-as-the-delimiter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!