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
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct s_String {
//Notre chaine
char *str;
//Nos Methodes
size_t (*length)(struct s_String *this);
char (*get)(struct s_String *this, int pos);
void (*replace)(struct s_String *this, int pos, char newChar);
void (*add)(struct s_String *this, char newChar);
void (*destroy)(struct s_String *this);
}String;
static size_t length(String *this) {
return strlen(this->str);
}
static char get(String *this, int pos) {
return this->str[pos];
}
static void destroy(String *this) {
free(this->str);
this->str = NULL;
}
static void replace(String *this, int pos, char newChar) {
this->str[pos] = newChar;
}
static void add(String *this, char newChar) {
char *newStr;
//Bien sur les mallocs doivents etre verifés
newStr = malloc(sizeof(char) * (this->length(this) + 2));
strcpy(newStr, this->str);
strncat(newStr, &newChar, 1);
free(this->str);
this->str = newStr;
}
String *create(char *s) {
String *this;
this = malloc(sizeof(String));
this->length = &length;
this->get = &get;
this->replace = &replace;
this->add = &add;
this->destroy = &destroy;
/* Copie de la chaine au cas ou c'est une chaine constante */
this->str = malloc((strlen(s) + 1) * sizeof(char));
strcpy(this->str, s);
return this;
}
int main(void) {
String *chaine = create("Coucou les amis");
printf("taille de la chaine : %zd\n", chaine->length(chaine));
printf("Le premier caractere est : %c\n", chaine->get(chaine, 0));
chaine->replace(chaine, 0, 'T');
printf("Je remplace le premiere char par un T\n");
printf("Le premier caractere est : %c\n", chaine->get(chaine, 0));
printf("J\'ajoute le caractere '&' a la fin de la chaine\n");
chaine->add(chaine, '&');
printf("La chaine est maintenant %s\n", chaine->str);
chaine->destroy(chaine);
free(chaine);
return 0;
} |
Partager