Hi guys i need your help for this replace_pattern program.
This is a program that takes a string
i.e.:"The boy was sitting in the room"
then it takes a string to compare
i.e.:"the"
Finally it takes a string to replace the second string
i.e:"a"
The final result is :"a boy was sitting in a room"
I must use this function:
char *replace_pattern(char *s, char *p ,char *np,int firstOnly);
Here is my program ...(i cant find what is wrong)
The bug is in replace_pattern function
/*memory allocation for the strings*/Code:#include<stdio.h> #include<string.h> char *replace_pattern(char *s, char *p ,char *np,int firstOnly); //this funct allocates dynamicly memory for the three strings //s,p and np char *mem_alloc(char *buffer); char buffer_str[81]; char *cur_str,*same_str,*repl_str,*new_str; int firstOnly,c; int main(void){ char *str_ptr; printf("Enter a string and then press enter...\n"); while( *(str_ptr=gets(buffer_str)) == NULL ) printf("try again...\n"); cur_str=mem_alloc(buffer_str); cur_str=buffer_str; printf("Enter a string to compare,then press enter...\n"); while( *(str_ptr=gets(buffer_str)) == NULL ) same_str=mem_alloc(buffer_str); same_str=buffer_str; printf("Enter a string to replace,then press enter...\n"); while( *(str_ptr=gets(buffer_str)) == NULL ) printf("try again...\n"); repl_str=mem_alloc(buffer_str); repl_str=buffer_str; printf("\nEnter 0 if you want to check the whole string..."); printf("\nor enter a different number if you want to find"); printf("\nand replace the 1st similarity:"); c=scanf("%d",&firstOnly); while(c!=1){ while((c=getchar())!='\n'); c=scanf("%d",&firstOnly); } new_str=replace_pattern(cur_str, same_str ,repl_str, firstOnly); return 0; }
Replace Pattern function *buggy one*Code:char *mem_alloc(char *buffer) { char *str; str=(char *)malloc((strlen(buffer)+1)); if(str==NULL){ printf("\n memory allocation error! "); printf("\n exiting now... "); exit(1); } else return(str); }
/* *s is the given string, *p is a string to search in *s,
if we find *p string in *s string we replace with *np string
if firstOnly !=0 i must replace only the first substring with np
else i must replace substrings with np string in the whole string*/
Code:char *replace_pattern(char *s, char *p ,char *np) { char *start_ptr; int counter=0,i=0,j=0; counter=strlen(p); while((start_ptr=strstr(s,p))!=NULL){ while(s<start_ptr) buffer_str[i++]=*s++; while(j<counter) buffer_str[i++]=*np++; s+=counter; } buffer_str[i++]='\0'; return buffer_str; }



LinkBack URL
About LinkBacks



