vlary
Platinum Member | Редактировать | Профиль | Сообщение | Цитировать | Сообщить модератору Berens Не понравилось мне то, что в таком варианте программа не обрабатывает множественные вхождения строки поиска в исходной строке. Вот модифицированный вариант. Код: /* replacetext.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> int replace_str(char *str, char *orig, char *rep, int pos) { int found=0; char temp[255]; char *cp = temp + pos; memset(temp,0,255); memcpy(temp,str,pos); char *xp=str+pos; char *sp=strstr(xp,orig); if(sp==NULL) return 0; while(sp!=NULL) { memcpy(cp,xp,(int)(sp-xp)); cp+=(int)(sp-xp); memcpy(cp,rep,strlen(rep)); cp+=strlen(rep); xp=sp+strlen(orig); sp=strstr(xp,orig); found++; } if(*xp!=0) strcat(cp,xp); else *cp=0; strcpy(str,temp); return found; } int main () { char txt[100][255], sin[255], sout[255], es[255]; int g,f,j,i,n,x,y,lensin,k; printf ("\nVvedite colichestvo strok:"); scanf ("%i",&n); getchar(); printf ("%d\nVvedite TEXT:",n); gets(es); for (i=0;i<=n;i++) strcpy(txt[i],es); printf ("\nVvedite stroky dlya poiska:"); gets (sin); printf ("\nVvedite stroky dlya zameny:"); gets (sout); printf ("\nS kakoi stroki zamenyat?:"); scanf ("%i",&y); printf ("\nS kakoi pozicii zamenyat?:"); scanf ("%i",&x); for (j=y;j<=n;j++) { replace_str(txt[j],sin,sout,x); } for (i=0;i<=n;i++) printf("\n%s",txt[i]); printf ("\n"); return 0; } | Вот результат: bash-3.2$ replacetext Vvedite colichestvo strok:12 12 Vvedite TEXT:the bad the mad the crazy world Vvedite stroky dlya poiska:the Vvedite stroky dlya zameny:this S kakoi stroki zamenyat?:5 S kakoi pozicii zamenyat?:4 the bad the mad the crazy world the bad the mad the crazy world the bad the mad the crazy world the bad the mad the crazy world the bad the mad the crazy world the bad this mad this crazy world the bad this mad this crazy world the bad this mad this crazy world the bad this mad this crazy world the bad this mad this crazy world the bad this mad this crazy world the bad this mad this crazy world the bad this mad this crazy world Вариант, естественно, наколенный, без проверок номеров, границ и т.д. Но это уже ты сам.
---------- Заслуженный SCOтовод, почетный SUNтехник и любитель Кошек |
|