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; }




Reply With Quote