Création d'une classe cl_string (gestion des chaînes)

Description

Je sais qu'il existe une class string.h mais j'ai voulu
recréer comme exercice une classe qui fait la même chose
mais peut être différemment.
On apprend :
-Une gestion dynamique de la mémoire (chaîne de caractères).
-Les fonction amies.
-Conversions de fonctions VB en C++ (insStr,len, mid, trim etc...).
Pas de prétention en vue juste un bon exercice.

compilation C++ Borland 5.5 (comme d'habitude)

Source / Exemple :


#include <windows>
  #include <iostream.h>

  #define mess_err200 "\nErreur 200 : Probleme d'allocation memoire.\n"
  #define mess_err102 "\nErreur : 102 - Probleme de parametres.\n"
  #define mess_err103 "\nErreur : 103 - Element inconnu.\n"
  #define blank  ' '
  #define blank0 '\0'

  typedef struct{
     int debut;
     int fin;
  }Split; 

  class Cl_String;

//--------------------------------------------------------
// Auteur            : UKR6900
// Date début        : 29/05/2006
// Date dernière MAJ : 29/05/2006
// Description       : Gestion de chaine
//--------------------------------------------------------
//                      DEBUT CLASSE Cl_String
//--------------------------------------------------------
  class Cl_String{
    private:
      char *chaine;
      int length;
        
    public:
      Cl_String();
      Cl_String(const char *);
      Cl_String(const Cl_String &);
      ~Cl_String();
      int len()const;
      Cl_String & Append(const Cl_String& rCh){
      //ajoute rCh a this
        return *this;
      };//end 
      friend ostream & operator << (ostream &,const Cl_String &);
      Cl_String & operator = (const Cl_String &);
      Cl_String operator = (const char * Ch);
      friend boolean operator == (const Cl_String &,const Cl_String &);
      friend boolean operator == (const Cl_String &,const char *);
      friend boolean operator != (const Cl_String &,const Cl_String &);
      friend boolean operator != (const Cl_String &,const char *);
      friend Cl_String operator + (const Cl_String &,const Cl_String &);
      Cl_String & operator += (const Cl_String & Ch);    
      friend Cl_String& operator += (Cl_String& rDest, const Cl_String& rSrc);
    
      friend Cl_String mid(const Cl_String &,int,int);
      friend Cl_String right(const Cl_String &,int);
      friend Cl_String left(const Cl_String &,int);
      friend Cl_String trim(const Cl_String &);
      friend Cl_String rtrim(const Cl_String &);
      friend Cl_String ltrim(const Cl_String &);
      friend int instr(const Cl_String &,const Cl_String &);
      friend int instr(const Cl_String &,const char *);
      friend Cl_String split(Cl_String &, const int,const char);
      friend Cl_String * split(Cl_String &,const char);
   };
//--------------------------------------------------------
//                      FIN CLASSE Cl_String
//--------------------------------------------------------
//------------------------------------------------------------------------------
// FONCTION      : Constructeur
// DESCRIPTION   : Constructeur par défaut
//-------------------------------------------------------------------------------
  Cl_String::Cl_String():chaine(NULL),length(0){
  }//end procedure

//------------------------------------------------------------------------------
// FONCTION      : Constructeur
// DESCRIPTION   : Constructeur par initialisation d'une chaine
//-------------------------------------------------------------------------------
  Cl_String::Cl_String(const char * Ch){
    length = strlen(Ch);
    chaine = new char[length+1];
    for (int i=0; i < length; i++){
      chaine[i] = Ch[i];
    }//end for
    chaine[length] = '\0';
  }//end procedure

//------------------------------------------------------------------------------
// FONCTION      : Constructeur
// DESCRIPTION   : Constructeur à partir d'un objet
//-------------------------------------------------------------------------------
  Cl_String::Cl_String(const Cl_String & rCh):chaine(NULL),length(0){
    chaine = new char[rCh.length+1];
    for (int i=0; i < rCh.length; i++){
      chaine[i] = rCh.chaine[i];
    }//end for
    length = rCh.length;
    chaine[length] = '\0';
  }//end procedure

//------------------------------------------------------------------------------
// FONCTION      : Destructeur
// DESCRIPTION   : Destruction de l'objet
//-------------------------------------------------------------------------------
  Cl_String::~Cl_String(){
    if (chaine != NULL){
      delete [] chaine;
    }//end if
  }//end procedure

//------------------------------------------------------------------------------
// FONCTION      : ostream
// DESCRIPTION   : affichage d'une chaine de caractère avec "cout << a << endl;"
//-------------------------------------------------------------------------------
  ostream & operator << (ostream & sortie,const Cl_String & p){
    if (p.chaine != NULL) {
      sortie << p.chaine;
    }
    return sortie;
  }//end procedure

//------------------------------------------------------------------------------
// FONCTION      : size
// DESCRIPTION   : donne la taille de la chaine
//-------------------------------------------------------------------------------
  int Cl_String::len()const{//- « const » ici indique que cette fonction ne va pas modifier les attributs de ta classe
    return this->length;
  }//end procedure

//------------------------------------------------------------------------------
// FONCTION      : operator =
// DESCRIPTION   : Cl_String = Cl_String = Cl_String ....
//-------------------------------------------------------------------------------
  Cl_String & Cl_String::operator = (const Cl_String & rCh){
  //Realocation de memoire dynamique
    if (length > 0) delete [] chaine;
    chaine = new char[rCh.length+1];
    
    if (chaine != NULL){
    //Transfert de la nouvelle chaine
      length = rCh.length;
      for (int i = 0; i < length; i++){
        chaine[i] = rCh.chaine[i];
      }//end for
      chaine[length] = '\0';
    }else
       printf(mess_err200);
    //end if*/
    return *this;
  }//end procedure

//------------------------------------------------------------------------------
// FONCTION      : operator =
// DESCRIPTION   : Cl_String = chaine
//-------------------------------------------------------------------------------
  Cl_String Cl_String::operator = (const char * Ch){
    Cl_String tampon(Ch);
    for (int i = 0; i < tampon.length; i++){
        chaine[i] = tampon.chaine[i];
      }//end for
    length=tampon.length;
    return tampon;
  }//end procedure

//------------------------------------------------------------------------------
// FONCTION      : operator ==
// DESCRIPTION   : Cl_String == Cl_String
//-------------------------------------------------------------------------------
  boolean operator == (const Cl_String &rCh1,const Cl_String &rCh2){
    if (rCh1.length == rCh2.length){
      for (int i = 0; i < rCh1.length; i++){
        if (rCh1.chaine[i] != rCh2.chaine[i]){
          return FALSE;
        }//end if
      }//end for
      return TRUE;  
    }//end if
    return FALSE; 
  }//end procedure

//------------------------------------------------------------------------------
// FONCTION      : operator ==
// DESCRIPTION   : Cl_String == chaine
//-------------------------------------------------------------------------------
  boolean operator == (const Cl_String &rCh1,const char * Ch2){
    Cl_String buffer(Ch2);
    if (rCh1 == buffer){
      return TRUE; 
    }//end if
    return FALSE; 
  }//end procedure

//------------------------------------------------------------------------------
// FONCTION      : operator !=
// DESCRIPTION   : Cl_String != Cl_String
//-------------------------------------------------------------------------------
  boolean operator != (const Cl_String &rCh1,const Cl_String &rCh2){
    if (rCh1.length == rCh2.length){
      for (int i = 0; i < rCh1.length; i++){
        if (rCh1.chaine[i] != rCh2.chaine[i]){
          return TRUE;
        }//end if
      }//end for
      return FALSE;  
    }//end if
    return TRUE; 
  }//end procedure

//------------------------------------------------------------------------------
// FONCTION      : operator !=
// DESCRIPTION   : Cl_String != chaine
//-------------------------------------------------------------------------------
  boolean operator != (const Cl_String &rCh1,const char * Ch2){
    Cl_String buffer(Ch2);
    if (rCh1 == buffer){
      return FALSE; 
    }//end if
    return TRUE; 
  }//end procedure

//------------------------------------------------------------------------------
// FONCTION      : operator +
// DESCRIPTION   : Cl_String + Cl_String
//-------------------------------------------------------------------------------
  Cl_String operator + (const Cl_String &rCh1,const Cl_String &rCh2){
    Cl_String Buffer;

    int Totlength,i;

    Totlength = rCh1.length + rCh2.length;
  //Realocation de memoire dynamique
    if (Totlength > 0){
      Buffer.chaine = new char[Totlength];
    }else 
      Buffer.chaine = NULL;
    //end if
    if (Buffer.chaine != NULL){
    //Transfert de la nouvelle chaine
      for (i = 0; i < rCh1.length; i++){
        Buffer.chaine[i] = rCh1.chaine[i];
      }//end for
      for (int j = 0; j < rCh2.length; j++){
        Buffer.chaine[j+i] = rCh2.chaine[j];
      }//end for
      Buffer.length = Totlength;
    }else
       printf(mess_err200);
    //end if
    return Buffer;
  }//end procedure

//------------------------------------------------------------------------------
// FONCTION      : operator +=
// DESCRIPTION   : Cl_String += Cl_String 
//-------------------------------------------------------------------------------
  Cl_String &  Cl_String::operator += (const Cl_String & Ch){

  • this = *this + Ch;
return *this; }//end procedure //------------------------------------------------------------------------------ // FONCTION : operator += // DESCRIPTION : Cl_String += Cl_String //------------------------------------------------------------------------------- Cl_String& operator += (Cl_String& rDest, const Cl_String& rSrc){ return rDest.Append(rSrc); }//end procedure //---------------------------------------------------------------------------- // FONCTION : mid // DESCRIPTION : Selectionne une partie d'une chaine avec un point de depart // et une longueur de chaine la chaine initiale (pos depart 0) //---------------------------------------------------------------------------- Cl_String mid(const Cl_String & rCh,int debut,int fin){ int i; Cl_String Buffer; //Controle le depassement de la table i = debut + fin; if ((i > rCh.length) || (fin < 0) || (debut < 0)){ printf(mess_err102); return Buffer; }//end if if (rCh.chaine != NULL){ //Transfert de l'adresse d'un caractere vers le premier de la chaine Buffer.chaine = new char[fin+1]; for (i = 0; i < fin; i++){ Buffer.chaine[i] = rCh.chaine[debut+i]; }//end for Buffer.chaine[fin] = blank0; //indication de fin de chaine Buffer.length = fin; }else printf(mess_err200); //end if return Buffer; }//end procedure //---------------------------------------------------------------------------- // FONCTION : right // DESCRIPTION : Selectionne une partie d'une chaine à partir de la droite // et une longueur de chaine //---------------------------------------------------------------------------- Cl_String right(const Cl_String & rCh, int fin){ int i; Cl_String Buffer; //Controle le depassement de la table if ((fin > rCh.length) || (fin < 0)){ printf(mess_err102); return Buffer; }//end if if (rCh.chaine != NULL){ //Transfert de l'adresse d'un caractere vers le premier de la chaine Buffer.chaine = new char[fin+1]; for (i=1; i<=fin; i++){ Buffer.chaine[fin-i] = rCh.chaine[rCh.length-i]; }//end for Buffer.chaine[fin] = blank0; Buffer.length = fin; }else printf(mess_err200); //end if return Buffer; }//end procedure //---------------------------------------------------------------------------- // FONCTION : left // DESCRIPTION : Selectionne une partie d'une chaine à partir de la gauche // et une longueur de chaine //---------------------------------------------------------------------------- Cl_String left(const Cl_String & rCh, int fin){ int i; Cl_String Buffer; //Controle le depassement de la table if ((fin > rCh.length) || (fin < 0)){ printf(mess_err102); return Buffer; }//end if if (rCh.chaine != NULL){ //Transfert de l'adresse d'un caractere vers le premier de la chaine Buffer.chaine = new char[fin+1]; for (i=0; i<fin; i++){ Buffer.chaine[i]= rCh.chaine[i]; }//end for Buffer.chaine[fin] = blank0; Buffer.length = fin; }else printf(mess_err200); //end if return Buffer; }//end procedure //------------------------------------------------------------------------------ // FONCTION : trim // DESCRIPTION : Enleve les blancs à droite et à gauche //------------------------------------------------------------------------------- Cl_String trim(const Cl_String & rCh){ int i,c,d; Cl_String Buffer; //Controle partie droite c = 0; for (i=1; i<rCh.length; i++){ if (rCh.chaine[rCh.length-i]==blank) c++; else break; //end if }//end for //Controle partie gauche d =0; for (i=0; i<rCh.length; i++){ if (rCh.chaine[i]==blank) d++; else break; //end if }//end for Buffer = mid(rCh,d,rCh.length-c-d); return Buffer; }//end procedure //------------------------------------------------------------------------------ // FONCTION : rtrim // DESCRIPTION : Enleve les blancs à droite //------------------------------------------------------------------------------- Cl_String rtrim(const Cl_String & rCh){ int i,c; Cl_String Buffer; //Transfert de l'adresse d'un caractere vers le premier de la chaine c = 0; for (i=1; i<rCh.length; i++){ if (rCh.chaine[rCh.length-i]==blank) c++; else break; //end if }//end for Buffer = mid(rCh,0,rCh.length-c); return Buffer; }//end procedure //------------------------------------------------------------------------------ // FONCTION : ltrim // DESCRIPTION : Enleve les blancs à gauche //------------------------------------------------------------------------------- Cl_String ltrim(const Cl_String & rCh){ int i,c; Cl_String Buffer; //Transfert de l'adresse d'un caractere vers le premier de la chaine c = 0; for (i=0; i<rCh.length; i++){ if (rCh.chaine[i]==blank) c++; else break; //end if }//end for Buffer = mid(rCh,c,rCh.length-c); return Buffer; }//end procedure //------------------------------------------------------------------------------ // FONCTION : instr // DESCRIPTION : Fournit la premiere position d'une occurence objet (pos depard 0) //------------------------------------------------------------------------------- int instr(const Cl_String & rChS,const Cl_String & rChR){ int d,i,p; Cl_String Buffer; if (rChR.chaine == NULL){ printf(mess_err102); return -1; }//end if d = rChS.length - rChR.length + 1; for (i = 0; i < d; i++){ Buffer = mid(rChS,i,rChR.length); p = 0; for (int j = 0; j < rChR.length; j++) if (Buffer.chaine[j] == rChR.chaine[j]) p++; //end for if (p == rChR.length) return i; }//end for return -1; }//end procedure //------------------------------------------------------------------------------ // FONCTION : instr // DESCRIPTION : Fournit la premiere position d'une occurence chaine (pos depard 0) //------------------------------------------------------------------------------- int instr(const Cl_String & rChS,const char * ch){ Cl_String ChR(ch); if (rChS.chaine == NULL){ printf(mess_err102); return -1; }//end if return instr(rChS,ChR); }//end procedure //------------------------------------------------------------------------------ // FONCTION : split // DESCRIPTION : Explose une chaine de caractère suivant un separateur et renvoie // les éléments récupérés sous forme de table //------------------------------------------------------------------------------- Cl_String * split (Cl_String & rCh,const char c){ int Nbrc,i; int v = 0; int d,f; //Enléve les blancs parasite dans la chaine trim(rCh); //Compte les mots suivant le séparateur for (i=0; i<rCh.length; i++){ if (rCh.chaine[i]==c) Nbrc++; //end if }//end for //Création d'une table Cl_String pour réceptionner le Split de la chaine Cl_String * splitTab = new Cl_String[Nbrc++]; //Initialisation de la structure dynamique elt 1 Split * s = new Split[Nbrc]; s[0].debut = 0; s[0].fin = 0; //Split de la chaine for (i=0;i < rCh.length;i++){ if (rCh.chaine[i] == c){ s[v].fin = i - s[v].debut; v++; if(v<=Nbrc+1) s[v].debut = i+1; }//end if }//end for //Correction de positionnement s[v].fin = rCh.length - s[v].debut; //Extraction de la chaine de caractère selectionnée et mise dans la table for (i=0; i<Nbrc; i++){ d = s[i].debut; f = s[i].fin; splitTab[i] = mid(rCh,d,f); }//end for // free(s); delete []s; return &splitTab[0]; }//end procedure //------------------------------------------------------------------------------ // FONCTION : split // DESCRIPTION : Explose une chaine de caractère suivant un separateur et le numéro de // l'élément à récupérer (pos depard 0) //------------------------------------------------------------------------------- Cl_String split (Cl_String & rCh, const int n,const char c){ Cl_String Buffer; Split * s; int CptSep = 0; //compteur de separateur int longueur,i; int v = 0; int d,f; rCh = trim(rCh); s = (Split *)malloc(sizeof(Split)); //Initialisation de la structure dynamique elt 1 s[0].debut = 0; s[0].fin = 1; //Compte le nombre de separateur dans la chaine for (i=0;i < rCh.length;i++){ if (rCh.chaine[i] == c) CptSep++; }//end for //Contrôle elt demandé if ((n < 0)||(n > CptSep)){ printf(mess_err103); return rCh; }//fin si //Reallocation mémoire pour mémoriser mon tableau dynamique de structure s = (Split *)realloc(s,(CptSep+1)*sizeof(Split)); //Split de la chaine for (i=0;i < rCh.length;i++){ if (rCh.chaine[i] == c){ s[v].fin = i - s[v].debut; v++; if(v<=CptSep+1) s[v].debut = i+1; }//end if }//end for //Correction de positionnement s[v].fin = rCh.length - s[v].debut; //Extraction de la chaine de caractère selectionnée d = s[n].debut; f = s[n].fin; free(s); Buffer = mid(rCh,d,f); return Buffer; }//end procedure //------------------------------------------------------------------------------ // START PROGRAM TEST CLASS //------------------------------------------------------------------------------- void main(){ Cl_String a("voiture boite suivant"),b(" revoir"),c(" A+"); // a=b; // cout << a << endl; /* cout << a.len() << endl; c = a ; cout << c << endl; if (a != b) cout << "ok" << endl; else cout << "not ok" << endl; //end if a += b+c; cout << a << endl; cout << mid(a,2,6) << endl; cout << right(a,6) << endl; cout << left(a,8) << endl; cout << trim(a) << "." << endl; cout << rtrim(a) << "." << endl; cout << ltrim(a) << "." << endl; cout << instr(a,"voit");*/ Cl_String * T = split(a,' '); cout << T[1] << endl; }//end programme //------------------------------------------------------------------------------ // END PROGRAM TEST CLASS //-------------------------------------------------------------------------------

Codes Sources

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.