字符串匹配问题

来源:互联网 发布:ai软件培训 编辑:程序博客网 时间:2024/05/21 22:58

问题:给定字符串“This is a string”,删除字符串中的“is”。

代码:

  1. /*return the remainder string*/
  2. char * matchstr(const char * src,const char *substr)
  3. {
  4.     const char * p = substr;
  5.     int i = 0;
  6.     int src_len = strlen(src);
  7.     int sub_len = strlen(substr);
  8.     int buf_len = src_len;
  9.     char *tmp_buf = new char[src_len+1];
  10.     char * buf = NULL;
  11.     while(*src!='/0')
  12.     {
  13.         const char * ptmp = strstr(src,p);
  14.         if(ptmp!=NULL){
  15.             while(src<ptmp)//copy strings which is befor ptmp postion into tmp_buf.
  16.             {
  17.                 tmp_buf[i]=*src;
  18.                 ++i;
  19.                 ++src;
  20.             }
  21.             src = src+sub_len;
  22.         }else{//if not match substr in src,then copy all string into tmp_buf
  23.             while(*src!='/0')
  24.             {
  25.                 tmp_buf[i]=*src;
  26.                 ++i;
  27.                 ++src;
  28.             }
  29.         }
  30.     }
  31.     tmp_buf[i]='/0';
  32.     buf_len = strlen(tmp_buf);
  33.     buf = new char[buf_len+1];
  34.     strcpy(buf,tmp_buf);
  35.     delete[] tmp_buf;
  36.     return buf;
  37. }

原创粉丝点击