Re: Traitement sur chaîne
Citation:
Envoyé par Fabouney
comment rajouter un caractère en plein milieu de la chaine ?
On ne sait pas pas facilement insérer dans une chaine, et le langage C n'est probablement pas le plus adapté pour ça (voir les scripts avec sed etc.).
Néanmoins, il y a des moyens.
Si le tableau de char est suffisament grand, on peut y arriver à coup de strchr() (recherche) et memmove() (deplacement avant insersion) un peu lent, mais assez simple...
Personellement j'utilise un objet 'maison' FSTR (Flexible STRing) qui me permet pas mal de manips 'souples' (pas besoin de gérer la taille, c'est automatique).
Ca reste quand même assez gore...
Code:
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;
} |
Sortie :
Code:
1 2 3 4 5 6
|
'"Hello" "world"'
pattern '"' found (4 time(s))
old size = 16
new size = 20
'""Hello"" ""world""' |
Et hop, deux fonctions en bibliothèque...
http://emmanuel-delahaye.developpez.com/clib.htm
Module STR