Results 1 to 3 of 3

Thread: optimize replace function in C

Threaded View

  1. #1

    Thread Starter
    New Member A_S_I_lepy's Avatar
    Join Date
    Jul 2008
    Location
    huh!
    Posts
    6

    Question optimize replace function in C

    hi every one-
    I made a replace function in C - the function is very stable and it works, but when it comes to large data, the function takes a long time.
    - is there any other way I can improve the speed of my function ??

    the following is my code

    Thanks in advance

    Code:
    char *_replace(char* source_str,char* search_str,char* replace_str,char* ostr , int *sz)
    {
    char *data = source_str;
    char *orgdata = data;
    char *_ostr = malloc(*sz);
    int ser_sz = strlen(search_str);
    int rep_sz = strlen(replace_str);
    int src_sz = strlen(source_str);
    int tempdata = 0;
    if (rep_sz > ser_sz){ 
    	int lstr = src_sz/ser_sz;
    	int tst = lstr * rep_sz;
        _ostr = malloc(lstr * rep_sz);
    }
    _ostr[0] = str_NULL;		/* remove garbage value */
    do{
      char *p = strstr(data,search_str);	/* get the pointer to the first occurrence */
    	if (!p){ 		
            break;
    	}
      strncat(_ostr,orgdata,p - orgdata);	/*append the rest of the string*/
      data = p + ser_sz;	/*ignore the search term*/
      strncat(_ostr,replace_str,rep_sz);	/* place the replace string*/
      orgdata = p + ser_sz;	/* save the current data*/
      }while(1);
    
      tempdata = strlen(orgdata);
      *sz = strlen(_ostr) + 1 + tempdata;
      ostr = malloc(*sz);
      ostr[0] = 0;
      strncpy(ostr,_ostr,*sz);  
      strncat(ostr,orgdata,tempdata);	/*append the rest*/
      free(_ostr);
      *sz = *sz - 1;
    return ostr;
    }
    Last edited by A_S_I_lepy; Jul 26th, 2008 at 08:20 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width