|
|
1.1 ! root 1: /* ! 2: * replace(s1, pat, s3, all, matcher) ! 3: * find pat in s1 and replace it with s3 ! 4: * return the result in a new malloced string. ! 5: * or NULL if s1 not in pat. Set all to 1 to ! 6: * replace all occurances 0 to replace the first. ! 7: */ ! 8: #include "misc.h" ! 9: ! 10: char * ! 11: replace(s1, pat, s3, all, matcher) ! 12: char *s1, *pat, *s3; ! 13: int all; ! 14: char * (*matcher)(); ! 15: { ! 16: int i; ! 17: char *w1, *w2, *w3, *w; ! 18: ! 19: if(NULL == (w2 = (*matcher)(s1, pat, &w3))) ! 20: return(NULL); ! 21: w = w1 = alloc(strlen(s1) + 1 + (i=strlen(s3)) + (int)ptrdiff(w2, w3)); ! 22: for(; s1 != w2;) ! 23: *w1++ = *s1++; ! 24: strcpy(w1, s3); ! 25: if(!all || (NULL == (w2 = replace(w3, pat, s3, all, matcher)))) { ! 26: strcpy(w1 + i, w3); ! 27: return(w); ! 28: } ! 29: strcpy((w3 = alloc(strlen(w2) + 1 + (i = strlen(w)))), w); ! 30: free(w); ! 31: strcpy(w3 + i, w2); ! 32: free(w2); ! 33: return(w3); ! 34: } ! 35: #ifdef TEST ! 36: extern char *strstr(); ! 37: ! 38: /* ! 39: * function to find by string ! 40: */ ! 41: char * ! 42: strfind(s1, s2, fin) ! 43: char *s1, *s2, **fin; ! 44: { ! 45: char *w1; ! 46: ! 47: if(NULL == (w1 = strstr(s1, s2))) ! 48: return(NULL); ! 49: *fin = w1 + strlen(s2); ! 50: return(w1); ! 51: } ! 52: ! 53: main() ! 54: { ! 55: if(yn("Match by pattern ")) ! 56: for(;;) { ! 57: char s1[80], pat[80], s3[80], *s; ! 58: int all; ! 59: ! 60: ask(s1, "S1 "); ! 61: if(!strcmp(s1, "quit")) ! 62: exit(0); ! 63: ask(pat, "pat"); ! 64: ask(s3, "S3 "); ! 65: all = yn("all"); ! 66: if(NULL == (s = replace(s1, pat, s3, all, match))) ! 67: printf("Not found\n"); ! 68: else { ! 69: printf("%s\n", s); ! 70: free(s); ! 71: } ! 72: } ! 73: else ! 74: for(;;) { ! 75: char s1[80], s2[80], s3[80], *s; ! 76: int all; ! 77: ! 78: ask(s1, "S1"); ! 79: if(!strcmp(s1, "quit")) ! 80: exit(0); ! 81: ask(s2, "S2"); ! 82: ask(s3, "S3"); ! 83: all = yn("all"); ! 84: if(NULL == (s = replace(s1, s2, s3, all, strfind))) ! 85: printf("Not found\n"); ! 86: else { ! 87: printf("%s\n", s); ! 88: free(s); ! 89: } ! 90: } ! 91: } ! 92: #endif
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.