Subject: Re: 4GL "replace" function Date: Fri, 11 May 2001 16:23:08 -0700 (PDT) From: Jonathan Leffler To: IIUG Software Archive , Informix NewsGroup On Fri, 11 May 2001, Ed Brown wrote: >Has anyone ever coded/seen/used a C-code function for 4GL that can replace >text within a string? Something like: > >LET string1 = REPLACE (source_string, search_for, replace_with) > >so that: > >LET string1 = REPLACE ("ABCDEFG", "CD", "XYZ") > >would result in string1 having a value of "ABXYZEFG" > >I looked on the IIUG site and didn't see anything in the software repository >there. The attachment contains a global search and replace I wrote and used a long time ago. It translates "ABCDEFGCDHIJKLCDMN" to "ABXYZEFGXYZHIJKLXYZMN", and apart from the name matches your calling semantics. It's still in K&R C because it pre-dates the original C standard. However, I see that the compiler I used did have some support for 'void'. That was probably on SCO Xenix. -- Yours, Jonathan Leffler (Jonathan.Leffler@Informix.com) #include Guardian of DBD::Informix v1.00.PC1 -- http://www.perl.com/CPAN "I don't suffer from insanity; I enjoy every minute of it!" /* @(#) File: $RCSfile: editstr.c,v $ @(#) Version: $Revision: 1.1 $ @(#) Last changed: $Date: 1988/10/03 13:22:18 $ @(#) Purpose: I4GL: Globally substitute substring in string @(#) Author: J Leffler */ /* edit_string: globally substitute for a substring in a string */ /* I4GL: LET new_string = edit_string(old_string, sub, rep) */ int edit_string(i) int i; { char old[512]; char new[512]; char sub[32]; char rep[32]; char *src; char *dst; char *s; char *t; int l_rep; int l_sub; extern char *strpat(); extern char *strn_cat(); if (i != 3) { retquote(""); return(1); } popstring(rep, sizeof(rep)); popstring(sub, sizeof(sub)); popstring(old, sizeof(old)); dst = new; src = old; l_sub = strlen(sub); *dst = '\0'; while ((s = strpat(src, sub)) != 0) { dst = strn_cat(dst, src, s-src+1); dst = strn_cat(dst, rep); src = s + l_sub; } (void)strn_cat(dst, src, sizeof(new)); /* tack on tail string */ retquote(new); return(1); } static char *strn_cat(d, s, n) register char *d; /* Out: string to be appended to */ register char *s; /* In: string to append */ register int n; /* In: maximum characters to copy */ { while (*d) d++; while (*s && --n > 0) *d++ = *s++; *d = '\0'; return(d); } static char *strpat(s, p) register char *s; /* In: string to search */ register char *p; /* In: string to search for */ { char *t; register char c; char *u; c = *p; while (*s) { if (*s == c) { t = s; u = p; while (*u && *u++ == *t++) ; if (*u == '\0') return(s); /* match found */ } s++; } return(0); /* no match */ }