StrSubst functions

Gene Michael Stover

created Tuesday, 19 October 2004
updated Tuesday, 19 October 2004

Copyright © 2004 Gene Michael Stover. All rights reserved. Permission to copy, store, & view this document unmodified & in its entirety is granted.


Contents

1 Introduction

At the different programming contracts I work, I often need a function to replace a substring with another string. Instead of writing one each time, I've written it once. Instead of putting it in some library & forgetting about it, I put it here.

2 License

The source code for each of these functions is copyrighted by Gene Michael Stover & is licensed according to the terms of the Gnu Lesser General Public License (LGPL).

3 C

This version for C assumes you reserve memory from the dynamic memory pool with function called xmalloc & return the memory to that pool with xfree. xmalloc works like malloc; xfree works like free. If you don't have your own implementations of xmalloc & xfree, you might do this:

/* Easy way to implement xmalloc & xfree as malloc & free */
#define xmalloc malloc
#define xfree free

Here is the C source code for StrSubst itself.

/*
 * Copyright (c) 2004 Gene Michael Stover.  All rights reserved.
 */
/*
 * Given a string, a source substring, & a destination substring, return
 * a new string in which the first occurrence of the source substring
 * has been replaced with the destination substring. If there is no
 * occurrence of the source substring, you get a copy of the original
 * string with no changes. To replace multiple occurrences, call this
 * function multiple times, each time with the last string returned by
 * the previous function call.
 *
 * Caller must free the new string with 'xfree'.
 */
char *
StrSubst (big, src, dst)
     char big[];
     char src[]
     char dst[];
{
  char *str = NULL, *p;

  p = strstr (big, src);
  if (p != NULL) {
    str = (char *) xmalloc (strlen (big) - strlen (src) + strlen (dst) + 1);
    sprintf (str, ``%*s%s%s'', p - big, big, dst, p + strlen (src));
  } else {
    /*
     * Didn't find the src string at all, so return a copy of the big
     * string.
     */
    str = xstrdup (big);
  }
  return str;
}

4 Lisp

Guess what: I haven't done the Lisp implementation yet.

A. Other File Formats

Gene Michael Stover 2008-04-20