Thread: str_replace

  1. #1
    Registered User
    Join Date
    May 2009
    Posts
    1

    str_replace

    Hello,

    I am using the following str_replace function -:

    Code:
    char * str_replace(char *haystack,char *needle,char *rstr) {
       size_t size=strlen(haystack)+1;
       char *p[size+1];
       char *ptrp=p;
       char *newstr;
       char *match;
       char *replace;
       int i,j;
       if (p==NULL){
          return(p);
       }
       newstr=haystack;
       while (*newstr){
          match=needle;
          replace=rstr;
          i=0;
          while(*newstr && *match){
             if(*newstr != *match){
                *ptrp++=*newstr++;
                match=needle;
                i=0;
             } else if(*newstr==*match){
                *ptrp++=*newstr++;
                match++;
                i++;
             }
          }
          if(i==(int)strlen(needle)){
             j=0;
             while(j<i){
                ptrp--;
                j++;
             }
             while(*replace){
                *ptrp++=*replace++;
             }
          }
       }
    
       *ptrp='\0';
       return(p);
    }
    Which works great, however, it does not seems to work if I want to remove "(" or ")" characters.

    Any any ideas why?

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    char *p[size+1];
    This is an array of pointers to characters.
    Code:
       if (p==NULL){
          return(p);
       }
    It can't ever be NULL. Also, you should try compiling with warnings, because I doubt you want to be trying to return that, even if it is somehow NULL.
    Code:
     while(*newstr && *match){
             if(*newstr != *match){
                *ptrp++=*newstr++;
                match=needle;
                i=0;
             } else if(*newstr==*match){
    Why is there an IF check there?

    That'll get you started.

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed