Before seeing the solution make sure that you tried enough. Don’t paste the whole code, just find out the logic. If you stuck in trouble, just inform me on comment.
/**Bismillahir Rahmanir Rahim.**/ #include <stdio.h> #include <string.h> int l_T, l_P, l_Q, x, y, move, k; int Index(char t[], char p[]) { int k=-1, r, s, max, l, m, cnt, i; s = strlen(t); r = strlen(p); max = s-r+1; for(i=0; i<max; i++) { if(t[i]==p[0]) { for(l=1, cnt=1, m=i+1; l<r; l++, m++) { if(p[l]==t[m]) cnt++; else break; } if(cnt==r) { k = i; break; } } } return k; } char *REPLACE_1(char t[], char p[], char q[], int k) { l_T = strlen(t); l_P = strlen(p); l_Q = strlen(q); move = l_Q-l_P; for(x=l_T-1; x>=k; x--) t[x+move] = t[x]; t[l_T+move] = '\0'; for(x=k, y=0; y<l_Q; x++,y++) t[x] = q[y]; return t; } char *REPLACE_2(char t[], char p[], char q[], int k) { l_T = strlen(t); l_P = strlen(p); l_Q = strlen(q); move = l_P-l_Q; for(x=k+move; x<l_T; x++) t[x-move] = t[x]; t[l_T-move] = '\0'; for(x=k, y=0; y<l_Q; x++,y++) t[x] = q[y]; return t; } int main() { char *T=malloc(sizeof(char)*5000); char P[1000], Q[1000]; printf("Please, Input Text.\n"); gets(T); printf("Please, Input What You Want To Remove.\n"); l_P = strlen(gets(P)); printf("Please, Input What You Want To Replace on Remove.\n"); l_Q = strlen(gets(Q)); for(k=Index(T,P); k!=-1; ) { if(l_P<l_Q) T = REPLACE_1(T,P,Q,k); else T = REPLACE_2(T,P,Q,k); k=Index(T,P); } printf("%s\n", T); free(T); return 0; }
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.