1
#include "string_util.h"
7
char* string_replace(const char* src, const char* from, const char* to)
10
* Find out the lengths of the source string, text to replace, and
11
* the replacement text.
14
size_t size = strlen(src) + 1;
15
size_t fromlen = strlen(from);
16
size_t tolen = strlen(to);
20
* Allocate the first chunk with enough for the original string.
22
char *value = malloc(size);
24
* We need to return 'value', so let's make a copy to mess around with.
29
* Before we begin, let's see if malloc was successful.
31
if ( value != NULL ) {
33
* Loop until no matches are found.
38
* Try to find the search text.
41
static const char word_chars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890_";
43
const char *match = strstr(src, from);
46
/* make sure there is a complete word */
51
ch_before = *(match-1);
54
if(src+strlen(src) >= match + fromlen){
55
ch_after = *(match + fromlen);
59
if(strchr(word_chars, ch_before) || strchr(word_chars, ch_after)){
64
if ( match != NULL && whole_word ) {
66
* Found search text at location 'match'. :)
67
* Find out how many characters to copy up to the 'match'.
69
size_t count = match - src;
72
* We are going to realloc, and for that we will need a
73
* temporary pointer for safe usage.
78
* Calculate the total size the string will be after the
79
* replacement is performed.
81
size += tolen - fromlen;
84
* Attempt to realloc memory for the new size.
86
temp = realloc(value, size);
90
* Attempt to realloc failed. Free the previously malloc'd
91
* memory and return with our tail between our legs. :(
98
* The call to realloc was successful. :) But we'll want to
99
* return 'value' eventually, so let's point it to the memory
100
* that we are now working with. And let's not forget to point
101
* to the right location in the destination as well.
103
dst = temp + (dst - value);
107
* Copy from the source to the point where we matched. Then
108
* move the source pointer ahead by the amount we copied. And
109
* move the destination pointer ahead by the same amount.
111
memmove(dst, src, count);
116
* Now copy in the replacement text 'to' at the position of
117
* the match. Adjust the source pointer by the text we replaced.
118
* Adjust the destination pointer by the amount of replacement
122
memmove(dst, to, tolen);
125
} else { /* No match found. */
127
* Copy any remaining part of the string. This includes the null
128
* termination character.
140
list_t* string_split(const char* src, const char* delim)
143
char *line = (char*)0;
144
char *ptr = (char*)src;
149
/* read the string as line by line */
150
line = strtok(ptr, "\n");
153
v = strstr(line, delim);
155
value = (char*)malloc(strlen(v+1)+1);
158
key = (char*)malloc(v - line + 1);
159
memcpy(key, line, v-line);
162
/* allocate string pair and append it to the list */
163
string_pair_t *pair = (string_pair_t*)malloc(sizeof(string_pair_t));
166
list_append(l, (void*)pair);
169
line = strtok((char*)0, "\n");