fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. typedef struct s_String {
  6. //Notre chaine
  7. char *str;
  8.  
  9. //Nos Methodes
  10. size_t (*length)(struct s_String *this);
  11. char (*get)(struct s_String *this, int pos);
  12. void (*replace)(struct s_String *this, int pos, char newChar);
  13. void (*add)(struct s_String *this, char newChar);
  14. void (*destroy)(struct s_String *this);
  15.  
  16. }String;
  17.  
  18. static size_t length(String *this) {
  19. return strlen(this->str);
  20. }
  21.  
  22. static char get(String *this, int pos) {
  23. return this->str[pos];
  24. }
  25.  
  26. static void destroy(String *this) {
  27. free(this->str);
  28. this->str = NULL;
  29. }
  30.  
  31.  
  32. static void replace(String *this, int pos, char newChar) {
  33. this->str[pos] = newChar;
  34. }
  35.  
  36. static void add(String *this, char newChar) {
  37. char *newStr;
  38.  
  39. //Bien sur les mallocs doivents etre verifés
  40. newStr = malloc(sizeof(char) * (this->length(this) + 2));
  41. strcpy(newStr, this->str);
  42. strncat(newStr, &newChar, 1);
  43. free(this->str);
  44. this->str = newStr;
  45. }
  46.  
  47. String *create(char *s) {
  48.  
  49. String *this;
  50.  
  51. this = malloc(sizeof(String));
  52. this->length = &length;
  53. this->get = &get;
  54. this->replace = &replace;
  55. this->add = &add;
  56. this->destroy = &destroy;
  57. /* Copie de la chaine au cas ou c'est une chaine constante */
  58. this->str = malloc((strlen(s) + 1) * sizeof(char));
  59. strcpy(this->str, s);
  60. return this;
  61. }
  62.  
  63. int main(void) {
  64. String *chaine = create("Coucou les amis");
  65. printf("taille de la chaine : %zd\n", chaine->length(chaine));
  66. printf("Le premier caractere est : %c\n", chaine->get(chaine, 0));
  67. chaine->replace(chaine, 0, 'T');
  68. printf("Je remplace le premiere char par un T\n");
  69. printf("Le premier caractere est : %c\n", chaine->get(chaine, 0));
  70. printf("J\'ajoute le caractere '&' a la fin de la chaine\n");
  71. chaine->add(chaine, '&');
  72. printf("La chaine est maintenant %s\n", chaine->str);
  73.  
  74. chaine->destroy(chaine);
  75.  
  76. free(chaine);
  77.  
  78. return 0;
  79. }
Success #stdin #stdout 0s 2380KB
stdin
Standard input is empty
stdout
taille de la chaine : 15
Le premier caractere est : C
Je remplace le premiere char par un T
Le premier caractere est : T
J'ajoute le caractere '&' a la fin de la chaine
La chaine est maintenant Toucou les amis&