1 /* str/join.c - Join two strings together
2 * Copyright (C) 2001 Bruce Guenter <bruceg@em.ca>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18 #include <string.h>
19 #include "str.h"
20
str_join(str * s,char sep,const str * in)21 int str_join(str* s, char sep, const str* in)
22 {
23 return str_joinb(s, sep, in->s, in->len);
24 }
25
str_joins(str * s,char sep,const char * in)26 int str_joins(str* s, char sep, const char* in)
27 {
28 return str_joinb(s, sep, in, strlen(in));
29 }
30
31 /* Join two strings together with exactly one instance of the seperator */
str_joinb(str * s,char sep,const char * in,unsigned len)32 int str_joinb(str* s, char sep, const char* in, unsigned len)
33 {
34 unsigned len1;
35 unsigned off2;
36 unsigned len2;
37
38 len1 = s->len;
39 while (len1 > 0 && s->s[len1-1] == sep) --len1;
40
41 off2 = 0;
42 while (off2 < len && in[off2] == sep) ++off2;
43 len2 = len - off2;
44
45 if (!str_realloc(s, len1+1+len2)) return 0;
46
47 s->s[len1++] = sep;
48 memcpy(s->s+len1, in+off2, len2);
49 s->len = len1 + len2;
50 s->s[s->len] = 0;
51 return 1;
52 }
53