1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static size_t count_patterns(char const *s_ori, char const *s_old)
{
size_t n = 0;
char const *p_beg = s_ori;
char const *p_end = s_ori;
while (p_end != NULL)
{
p_end = strstr(p_beg, s_old);
if (p_end != NULL)
{
n++;
p_beg = p_end + 1;
}
}
return n;
}
static char *str_replace_dyn (char const *s_ori, char const *s_old, char const *s_new)
{
char *s_mod = NULL;
size_t n_patterns = count_patterns(s_ori, s_old);
if (n_patterns != 0)
{
printf ("pattern '%s' found (%lu time(s))\n"
, s_old
, (unsigned long) n_patterns);
{
size_t size = strlen (s_ori)
+ ((strlen (s_new) - strlen (s_old)) * n_patterns)
+ 1;
printf ("old size = %lu\n"
"new size = %lu\n"
, (unsigned long) strlen (s_ori) + 1
, (unsigned long) size
);
s_mod = malloc (size);
if (s_mod != NULL)
{
char const *p_beg = s_ori;
char const *p_end = s_ori;
*s_mod = 0;
while (p_end != NULL)
{
p_end = strstr(p_beg, s_old);
if (p_end != NULL)
{
strncat(s_mod, p_beg, (size_t) (p_end - p_beg));
strcat(s_mod, s_new);
p_beg = p_end + 1;
}
else
{
strcat(s_mod, p_beg);
}
}
}
}
}
return s_mod;
}
int main(void)
{
char const *s = ("\"Hello\" \"world\"");
printf ("'%s'\n", s);
char *s_new = str_replace_dyn (s, "\"", "\"\"");
if (s_new != NULL)
{
printf ("'%s'\n", s_new);
free (s_new), s_new = NULL;
}
return 0;
} |
Partager