1 /* Part of publib.
2
3 Copyright (c) 1994-2006 Lars Wirzenius. All rights reserved.
4
5 Redistribution and use in source and binary forms, with or without
6 modification, are permitted provided that the following conditions
7 are met:
8
9 1. Redistributions of source code must retain the above copyright
10 notice, this list of conditions and the following disclaimer.
11
12 2. Redistributions in binary form must reproduce the above
13 copyright notice, this list of conditions and the following
14 disclaimer in the documentation and/or other materials provided
15 with the distribution.
16
17 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
18 OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
21 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
23 GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
25 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29 /*
30 * strsub.c -- substitute first occurence of pattern with another string
31 *
32 * Part of publib. See man page for more information
33 * "@(#)publib-strutil:$Id: strsub.c,v 1.1.1.1 1994/02/03 17:25:30 liw Exp $"
34 */
35
36 #include <assert.h>
37 #include <string.h>
38 #include "publib/strutil.h"
39
strsub(char * str,const char * pat,const char * sub)40 char *strsub(char *str, const char *pat, const char *sub) {
41 size_t lenpat, lensub, lenstr;
42
43 assert(str != NULL);
44 assert(pat != NULL);
45 assert(*pat != '\0');
46 assert(sub != NULL);
47
48 str = strstr(str, pat);
49 if (str == NULL)
50 return NULL;
51
52 lenstr = strlen(str);
53 lenpat = strlen(pat);
54 lensub = strlen(sub);
55
56 /* make room for substituted string, or remove slack after it */
57 if (lensub != lenpat)
58 memmove(str + lensub, str + lenpat, lenstr + 1 - lenpat);
59
60 memcpy(str, sub, lensub);
61 return str + lensub;
62 }
63