Page suivante Page précédente Table des matières

15. Annexe B String.h

Vous pouvez récupérer tous les programmes en un seul tar.gz sur Telecharger String . Pour obtenir ce fichier, dans un butineur web, sauvez ce fichier en type 'texte'.


//
// Auteur : Al Dev
// Utilisez la classe string ou cette classe
//
// Pour prévenir les fuites de mémoire - une classe caractère qui gère les
// variables caractère.
// Préférez toujours l'utilisation de la classe String à char[] et char *.
//

#ifndef __STRING_H_
#define __STRING_H_

//#include <iostream> // ne pas utiliser iostream car le programme devient volumineux.
//#include <stdlib.h> // pour free() et malloc()
#include <string.h> // pour strcpy()
#include <ctype.h> // pour isspace()
#include <stdio.h> // pour sprintf()
#include <list.h> // pour sprintf()
#include <math.h> // pour modf(), rint()

#include "my_malloc.h"
#include "debug.h" // debug_(name, value)  debug2_(name, value, LOG_YES)

const short INITIAL_SIZE =      50;
const short NUMBER_LENGTH = 70;
const int MAX_ISTREAM_SIZE = 2048;

class StringBuffer;

// une petite classe avec le STRICT MINIMUM de fonctions et de variables
// Cette classe doit être gardée petite...
class String
{
        public:
                String();
                String(char bb[]);  // nécessaire pour operator+
                String(char bb[], int start, int slength); // sous-ensemble de caractères
                String(int bb);  // nécessaire pour operator+
                String(unsigned long bb);  // nécessaire pour operator+
                String(long bb);  // nécessaire pour operator+
                String(float bb);  // nécessaire pour operator+
                String(double bb);  // nécessaire pour operator+
                String(const String & rhs);  // constructeur de recopie nécessaire pour operator+
                String(StringBuffer sb);  // compatibilité Java
                String(int bb, bool dummy);  // pour la classe StringBuffer
                ~String();

                char *val() {return sval;} // Pas sur de mettre sval publique

                // Les fonctions ci-dessous imitent le String de Java
                unsigned long length() { return strlen(sval); }
                char charAt(int where);
                void getChars(int sourceStart, int sourceEnd, 
                                char target[], int targetStart);
                char* toCharArray();
                char* getBytes();

                bool equals(String str2); // Voir aussi operator ==
                bool equals(char *str2); // Voir aussi operator ==
                bool equalsIgnoreCase(String str2);

                bool regionMatches(int startIndex, String str2, 
                                int str2StartIndex, int numChars);
                bool regionMatches(bool ignoreCase, int startIndex, 
                                String str2, int str2StartIndex, int numChars);

                String toUpperCase();
                String toLowerCase();

                bool startsWith(String str2);
                bool startsWith(char *str2);

                bool endsWith(String str2);
                bool endsWith(char *str2);

                int compareTo(String str2);
                int compareTo(char *str2);
                int compareToIgnoreCase(String str2);
                int compareToIgnoreCase(char *str2);

                int indexOf(char ch, int startIndex = 0);
                int indexOf(char *str2, int startIndex = 0);
                int indexOf(String str2, int startIndex = 0);

                int lastIndexOf(char ch, int startIndex = 0);
                int lastIndexOf(char *str2, int startIndex = 0);
                int lastIndexOf(String str2, int startIndex = 0);

                String substring(int startIndex, int endIndex = 0);
                String replace(char original, char replacement);
                String replace(char *original, char *replacement);

                String trim(); // Voir aussi trim() surcharge

                String concat(String str2);  // Voir aussi operator +
                String concat(char *str2); // Voir aussi operator +

                String reverse(); // Voir aussi reverse() surcharge
                String deleteCharAt(int loc);
                String deleteStr(int startIndex, int endIndex); // le "delete()" de Java

                String valueOf(char ch)
                        {char aa[2]; aa[0]=ch; aa[1]=0; return String(aa);}
                String valueOf(char chars[]){ return String(chars);}
                String valueOf(char chars[], int startIndex, int numChars);
                String valueOf(bool tf)
                        {if (tf) return String("true"); else return String("false");}
                String valueOf(int num){ return String(num);}
                String valueOf(long num){ return String(num);}
                String valueOf(float num) {return String(num);}
                String valueOf(double num) {return String(num);}

                // Voir aussi la classe StringBuffer plus bas

                // ---- Fin des fonctions à la Java -----

                /////////////////////////////////////////////////////////////
                // Liste des fonctions aditionnelles non présentes dans Java
                /////////////////////////////////////////////////////////////
                String ltrim();
                void ltrim(bool dummy); // dummy pour avoir une signature differente
                String rtrim();
                void rtrim(bool dummy); // dummy pour avoir une signature differente

                void chopall(char ch='\n'); // supprime les caractères 'ch' en fin
                void chop(); // supprime un caractère en fin

                void roundf(float input_val, short precision);
                void decompose_float(long *integral, long *fraction); 

                void roundd(double input_val, short precision);
                void decompose_double(long *integral, long *fraction); 

                void explode(char *seperator); // voir aussi token() et explode() surcharge
                String *explode(int & strcount, char seperator = ' '); // voir aussi token()
                void implode(char *glue);
                void join(char *glue);
                String repeat(char *input, unsigned int multiplier);
                String tr(char *from, char *to); // translate characters
                String center(int padlength, char padchar = ' ');
                String space(int number = 0, char padchar = ' ');
                String xrange(char start, char end);
                String compress(char *list = " ");
                String left(int slength = 0, char padchar = ' ');
                String right(int slength = 0, char padchar = ' ');
                String overlay(char *newstr, int start = 0, int slength = 0, char padchar = ' ');

                String at(char *regx); // renvoie la première occurrence de regx
                String before(char *regx); // renvoie la chaîne avant regx
                String after(char *regx); // renvoie la chaîne apres regx
                String mid(int startIndex = 0, int length = 0);

                bool isNull();  
                bool isInteger();
                bool isInteger(int pos);
                bool isNumeric();
                bool isNumeric(int pos);
                bool isEmpty();  // idem que length() == 0
                bool isUpperCase();
                bool isUpperCase(int pos);
                bool isLowerCase();
                bool isLowerCase(int pos);
                bool isWhiteSpace();
                bool isWhiteSpace(int pos);
                bool isBlackSpace();
                bool isBlackSpace(int pos);
                bool isAlpha();
                bool isAlpha(int pos);
                bool isAlphaNumeric();
                bool isAlphaNumeric(int pos);
                bool isPunct();
                bool isPunct(int pos);
                bool isPrintable();
                bool isPrintable(int pos);
                bool isHexDigit();
                bool isHexDigit(int pos);
                bool isCntrl();
                bool isCntrl(int pos);
                bool isGraph();
                bool isGraph(int pos);

                void clear();
                int toInteger();
                long parseLong();

                double toDouble();
                String token(char separator = ' '); // voir StringTokenizer, explode()
                String crypt(char *original, char *salt);
                String getline(FILE *infp = stdin); // voir aussi putline()
                //String getline(fstream *infp = stdin); // voir aussi putline()

                void putline(FILE *outfp = stdout); // voir aussi getline()
                //void putline(fstream *outfp = stdout); // voir aussi getline()

                void swap(String aa, String bb); // permute aa et bb
                String *sort(String aa[]);  // trie le tableau de chaînes
                String sort(int startIndex = 0, int length = 0);  // trie les caractères de la chaîne
                int freq(char ch); // retourne le nombre d'occurrences distinctes, non superposees
                void Format(const char *fmt, ...);
                String replace (int startIndex, int endIndex, String str);

                void substring(int startIndex, int endIndex, bool dummy);
                void reverse(bool dummy); // dummy pour avoir une signature differente
                String deleteCharAt(int loc, bool dummy);
                String deleteStr(int startIndex, int endIndex, bool dummy);
                void trim(bool dummy); // dummy pour avoir une signature differente
                String insert(int index, String str2);
                String insert(int index, String str2, bool dummy);
                String insert(int index, char ch);
                String insert(int index, char ch, bool dummy);
                String insert(char *newstr, int start = 0, int length = 0, char padchar = ' ');

                // requis par le StringBuffer de Java
                void ensureCapacity(int capacity);
                void setLength(int len);
                void setCharAt(int where, char ch);

                // requis par les classes Integer Long et Double de Java
                int parseInt(String ss) {return ss.toInteger();}
                int parseInt(char *ss)
                        {String tmpstr(ss); return tmpstr.toInteger();}
                long parseLong(String ss) {return ss.parseLong();}
                long parseLong(char *ss)
                        {String tmpstr(ss); return tmpstr.parseLong();}
                float floatValue() {return (float) toDouble(); }
                double doubleValue() {return toDouble(); }

                ///////////////////////////////////////////////
                //              Liste des fonctions dupliquées
                ///////////////////////////////////////////////
                // char * c_str() // utilisez val()
                // bool find();  // utilisez regionMatches()
                // bool search();  // utilisez regionMatches()
                // bool matches(); // utilisez regionMatches()
                // int rindex(String str2, int startIndex = 0); utilisez lastIndexOf()
                // String blanks(int slength);  // utilisez repeat()
                // String append(String str2); // utilisez concat() ou operator+
                // String prepend(String str2);  // utilisez operator+. Voir aussi append()
                // String split(char seperator = ' ');  // utilisez token()
                bool contains(char *str2, int startIndex = 0); // utilisez indexOf()
                // void empty(); utilisez is_empty()
                // void vacuum(); utilisez clear()
                // void erase(); utilisez clear()
                // void zero(); utilisez clear()
                // bool is_float(); utilisez is_numeric();
                // bool is_decimal(); utilisez is_numeric();
                // bool is_Digit(); utilisez is_numeric();
                // float float_value(); utilisez toDouble();
                // float tofloat(); utilisez toDouble();
                // double double_value(); utilisez toDouble();
                // double numeric_value(); utilisez toDouble();
                // int int_value(); utilisez toInteger()
                // int tonumber(); utilisez toInteger()
                // String get(); utilisez substring() ou val() mais preferrez le substring de Java
                // String getFrom(); utilisez substring() ou val() mais preferrez le substring de Java
                // String head(int len); utilisez substring(0, len)
                // String tail(int len); utilisez substring(length()-len, length())
                // String cut(); utilisez deleteCharAt() ou deleteStr()
                // String cutFrom(); utilisez deleteCharAt() ou deleteStr()
                // String paste(); utilisez insert()
                // String fill(); utilisez replace()
                // char firstChar(); // utilisez substring(0, 1);
                // char lastChar(); // utilisez substring(length()-1, length());
                // String findNext(); utilisez token()

                // begin();  iterator. utilisez operator [ii]
                // end();  iterator. utilisez operator [ii]
                // copy();  utilisez l'opérateur d'affectation, String aa = bb;
                // clone();  utilisez l'opérateur d'affectation, String aa = bb;

                // Tous les opérateurs ...
                String operator+ (const String & rhs);
                friend String operator+ (const String & lhs, const String & rhs);

                String& operator+= (const String & rhs); // utiliser une référence va plus vite
                String& operator= (const String & rhs); // utiliser une référence va plus vite
                bool operator== (const String & rhs); // utiliser une référence va plus vite
                bool operator== (const char *rhs);
                bool operator!= (const String & rhs);
                bool operator!= (const char *rhs); 
                char operator [] (unsigned long Index) const;
                char& operator [] (unsigned long Index);
                friend ostream &  operator<< (ostream & Out, const String & str2);
                friend istream &  operator>> (istream & In, String & str2);

                static  list<String>                 explodeH;  // tete de liste

        protected:
                char *sval; // Pas sûr de mettre sval publique
                inline void verifyIndex(unsigned long index) const;
                inline void verifyIndex(unsigned long index, char *aa) const;

                void _str_cat(char bb[]);
                void _str_cat(int bb);
                void _str_cat(unsigned long bb);
                void _str_cat(float bb);

        private:
                // Note : toutes les fonctions et variables privées ont des noms
                // commencant par _ (souligne)
                
                //static String *_global_String; // utilisé dans l'opérateur ajout
                //inline void _free_glob(String **aa);
                void _str_cpy(char bb[]);
                void _str_cpy(int bb); // itoa
                void _str_cpy(unsigned long bb);
                void _str_cpy(float bb); // itof

                bool _equalto(const String & rhs, bool type = false);
                bool _equalto(const char *rhs, bool type = false);
                String *_pString;  // pointeur temporaire pour usage interne
                inline void _allocpString();
                inline void _reverse();
                inline void _deleteCharAt(int loc);
                inline void _deleteStr(int startIndex, int endIndex);
                inline void _trim();
                inline void _ltrim();
                inline void _rtrim();
                inline void _substring(int startIndex, int endIndex);
};

// Imite StringBuffer de Java
// Cette classe est prévue pour que le code Java soit portable en C++ en ne
// nécessitant que peu de changements
// Note : si vous codez en C++, N'utilisez PAS cette classe StringBuffer,
// elle n'est fournie que pour compiler du code écrit en Java copié/collé
// dans du code C++.
class StringBuffer: public String
{
        public:
                StringBuffer();
                StringBuffer(int size);
                StringBuffer(String str);
                ~StringBuffer();

                int capacity() {return strlen(sval);}
                StringBuffer append(String str2)
                        { *this += str2; return *this;} // Voir aussi l'opérateur +
                StringBuffer append(char *str2)
                        { *this += str2; return *this;} // Voir aussi l'opérateur +
                StringBuffer append(int bb)
                        { *this += bb; return *this;} // Voir aussi l'opérateur +
                StringBuffer append(unsigned long bb) 
                        { *this += bb; return *this;} // Voir aussi l'opérateur +
                StringBuffer append(float bb) 
                        { *this += bb; return *this;} // Voir aussi l'opérateur +
                StringBuffer append(double bb) 
                        { *this += bb; return *this;} // Voir aussi l'opérateur +

                StringBuffer insert(int index, String str2)
                        { return String::insert(index, str2, true);}

                StringBuffer insert(int index, char ch)
                        { return String::insert(index, ch, true);}

                StringBuffer reverse()
                        { String::reverse(true); return *this;}

                // le "delete()"de Java. On ne peut pas utiliser le nom delete en C++
                StringBuffer deleteStr(int startIndex, int endIndex)
                        { String::deleteStr(startIndex, endIndex, true); return *this;}
                StringBuffer deleteCharAt(int loc)
                        { String::deleteCharAt(loc, true); return *this;}

                StringBuffer substring(int startIndex, int endIndex = 0)
                        { String::substring(startIndex, endIndex, true); return *this;}
};

static String Integer("0"); // Integer.parseInt(String) de Java
static String Long("0"); // Long.parseLong(String) de Java

// Imite la classe Float et Float.floatValue() de Java
// Est fournie pour compiler du code Java en C++.
class Float: public String
{
        public:
                Float(String str);
                Float valueOf(String str2) {return Float(str2);}
                float floatValue() {return (float) toDouble(); }
};

// Imite la classe Double de Java et Double.doubleValue()
// Est fournie pour compiler du code Java en C++.
class Double: public String
{
        public:
                Double(String str);
                Double valueOf(String str2) {return Double(str2);}
                double doubleValue() {return toDouble(); }
};

// Imite la classe StringTokenizer de Java
// Fournie pour compiler du code Java en C++ et vice-versa
class StringTokenizer: public String
{
        public:
                StringTokenizer(String str);
                StringTokenizer(String str, String delimiters);
                StringTokenizer(String str, String delimiters, bool dflag);
                ~StringTokenizer();

                int     countTokens();
                bool    hasMoreElements();
                bool    hasMoreTokens();
                String  nextElement(); // en Java retourne un 'Object'
                String  nextToken();
                String  nextToken(String delimiters);
        private:
                int             _current_position; // position courante dans la chaîne
                int             _total_tokens;
                int             _remaining_tokens;
                char *  _listofdl; // liste de delimiteurs
                char *  _workstr; // chaîne temporaire
                char *  _origstr; // chaîne originalement passée
                bool    _dflag;  // indicateur de delimiteur
                inline  void _prepworkstr(char *delimiters = NULL);
};

// Imite la classe StringReader de Java
// Fournie pour compiler du code Java en C++
class StringReader: public String
{
        public:
                StringReader(String str);
                void close() {}  // ferme le flux
                void mark(int readAheadLimit);
                bool markSupported() {return true;} // indique si le flux supporte l'opération mark(), il le fait
                int read();
                int read(char cbuf[], int offset, int length);
                bool ready() {return true;} // indique si le flux est prêt à être lu
                void reset();
                long skip(long ii);
        private:
                unsigned long   _curpos;
                unsigned long   _mark_pos;
};

// Imite la classe StringWriter de Java 
// fournie pour compiler du code Java en C++
class StringWriter: public String
{
        public:
                StringWriter();
                StringWriter(int bufferSize);
                void close() {clear();}
                void flush() {clear();}
                StringBuffer getBuffer() {return (StringBuffer) *this;}
                String  toString() {return (String) *this;}
                void write(int);
                void write(String);
                void write(char *str1);
                void write(char str1[], int startIndex, int endIndex);
                void write(String str1, int startIndex, int endIndex);
};

// Les variables globales sont définies dans String.cpp

#endif // __STRING_H_


Page suivante Page précédente Table des matières