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 pat replaced rep. note len(pat) can less than, greater than, or equal len(rep). function allocates memory resulting string, , caller free it. example, if call replace("fiore x", "x", "sucks"), returned new string fiore sucks (but remember, pat longer 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

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -