c - Replace String pattern with new string -
i use question...
char *replace(char *s, char *pat, char *rep)returns copy of string s, each instance of
patreplacedrep. notelen(pat)can less than, greater than, or equallen(rep). function allocates memory resulting string, , caller free it. example, if callreplace("fiore x", "x", "sucks"), returned new stringfiore sucks(but remember,patlonger individual character , occur multiple times).
i've managed determine whether pattern occurs in original string, run problem if pattern occurs more once. haven't got part of creating new string replaced text. i'm not allowed use functions <string.h>. (i'm still new c)
char *replace(char *s, char *pat, char *rep){ char *a = malloc(300); char *pa = s; int patlen = 0; int i; for(i = 0; pat[i] != '\0'; i++) { patlen++; } int oglen = patlen; while(*s != '\0') { if(*s == *pat) { s++; pat++; patlen--; while(*s == *pat) { s++; pat++; patlen--; } if(patlen == 0) { printf("this pattern"); patlen = oglen; } } s++; } return s; }
since can't use string.h functions, i'd write few string utility functions count string length, compare strings , copy strings. make code easier understand. i'd make 2 passes through string s: first time count occurrences of pat. can calculate size of new string: length(s) + occurrences * (length(rep) - length(pat). allocate new string. pass through string s again, copying new string whenever occurrence of pat found, copy rep instead. hope helps.
Comments
Post a Comment