/*
 *				r e p l a c . c
 */

/*)LIBRARY
*/

#ifdef	DOCUMENTATION

title	replace		Simple Character Translation
index			Simple character translation

synopsis

	 char *
	 replace(s,from,to)
	 char s[];
	 char from[];
	 char to[];

	 extern char rep_tab[256];

description

	replace() provides a simple interface to translate() and the functions
	associated with it; see transl.c for details.  Briefly, each character
	character in s that occurs in from is replaced by the corresponding
	character in to.  If there are more characters in from than in to,
	the "excess" characters are deleted from the output string.  replace()
	returns the output string in space allocated from malloc(); the input
	string is unchanged.  If replace() can't get the space it needs, it
	returns NULL.

	rep_tab is a global character table that is used in the internal calls
	to the translation routines.  It is large enough to translate any
	8-bit byte.  rep_tab is cleared and the set up on each call to
	replace().  If you intend to call replace() many times with the same
	second and third arguments, you can call it once to set up rep_tab and
	then call translate() directly - change subsequent s1 = replace(s,t,f)
	calls to translate(rep_tab,s1 = savestr(s)).

	Note: The power of a function like replace() is often not appreciated.
	If s is any 5-character string, then replace("abcde","edcba",s) is s
	reversed - i.e., this call maps "words" to "sdrow".  In general, if
	P is any permutation of n-character strings, n<256, then the call
	replace(b,P(b),s) returns P(s), where b is any (constant) string of
	length n containing n different characters.  (s, of course, is also of
	length n).  Thus, replace() implements character substitutions,
	deletions, and permutations, all in one small, simple to use function.

bugs

author

	Jerry Leichter

#endif

/*
 * )EDITLEVEL=03
 * Edit history
 * 0.0 30-Jun-81 JSL	Invention
 */

#define NULL 0

char rep_tab[256];

char *
replace(s,from,to)
register char s[];
register char from[];
register char to[];
{	clrttab(rep_tab,sizeof rep_tab - 1);
	setttab(rep_tab,from,to);
	if ((s = savestr(s)) != NULL)
	{	translate(rep_tab,s);
		realloc(s,strlen(s) + 1);
	}
	return(s);
}	
