326
|
1 /*
|
|
2 lw_string.c
|
|
3
|
|
4 Copyright © 2010 William Astle
|
|
5
|
|
6 This file is part of LWTOOLS.
|
|
7
|
|
8 LWTOOLS is free software: you can redistribute it and/or modify it under the
|
|
9 terms of the GNU General Public License as published by the Free Software
|
|
10 Foundation, either version 3 of the License, or (at your option) any later
|
|
11 version.
|
|
12
|
|
13 This program is distributed in the hope that it will be useful, but WITHOUT
|
|
14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
|
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
|
16 more details.
|
|
17
|
|
18 You should have received a copy of the GNU General Public License along with
|
|
19 this program. If not, see <http://www.gnu.org/licenses/>.
|
|
20 */
|
|
21
|
|
22 #include <config.h>
|
|
23
|
|
24 #include <string.h>
|
|
25 #include <stdlib.h>
|
|
26
|
|
27 #define ___lw_string_c_seen___
|
|
28 #include "lw_alloc.h"
|
|
29 #include "lw_string.h"
|
|
30
|
|
31 char *lw_strdup(const char *s)
|
|
32 {
|
|
33 char *r;
|
|
34
|
|
35 if (!s)
|
|
36 s = "(null)";
|
|
37
|
|
38 r = lw_alloc(strlen(s) + 1);
|
|
39 strcpy(r, s);
|
|
40 return r;
|
|
41 }
|
|
42
|
329
|
43 char *lw_strndup(const char *s, int len)
|
|
44 {
|
|
45 char *r;
|
|
46 int sl;
|
|
47
|
|
48 sl = strlen(s);
|
|
49 if (sl > len)
|
|
50 sl = len;
|
|
51
|
|
52 r = lw_alloc(sl + 1);
|
|
53 memmove(r, s, sl);
|
|
54 r[sl] = '\0';
|
|
55 return r;
|
|
56 }
|
|
57
|
326
|
58 char *lw_token(const char *s, int sep, const char **ap)
|
|
59 {
|
|
60 const char *p;
|
|
61 char *r;
|
|
62
|
|
63 if (!s)
|
|
64 return NULL;
|
|
65
|
|
66 p = strchr(s, sep);
|
|
67 if (!p)
|
|
68 {
|
|
69 if (ap)
|
|
70 *ap = NULL;
|
|
71 return lw_strdup(s);
|
|
72 }
|
|
73
|
|
74 r = lw_alloc(p - s + 1);
|
|
75 strncpy(r, (char *)s, p - s);
|
|
76 r[p - s] = '\0';
|
|
77
|
|
78 if (ap)
|
|
79 {
|
|
80 while (*p && *p == sep)
|
|
81 p++;
|
|
82 *ap = p;
|
|
83 }
|
|
84 return r;
|
|
85 }
|