Compter nombre caractère d'une chaîne
Bonjour tous le monde :
J'ai crée une class String.
J'aimerais faire une fonction qui me retournerais le nombre de caractère d'une chaîne.
j'ai donc fait cette fonction :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
int String::length()
{
int i = 0;
while (_string[i] != '\0')
{
cout << _string[i];
i++;
}
return i;
} |
Cependant j'ai une erreur, le programme ne retourne rien et bloque sur mon while.
Voici mon main:
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
|
int main (int argc, char * const argv[]) {
// insert code here...
String s1;
s1 = "hello ";
String s2 = s1;
s2 = "world";
String s3(", how are you");
//String s4 = '?';
//char* s5 = s3;
//cout << s5;
cout << s1 << s2 << s3 << endl ;
String s6;
int l6 = s6.length(); // l6 == 0 //ça bloque donc sur cette ligne
/*String s7 = "hello";
int l7 = s7.length(); // l7 == 5
//cout << l6;
//cout <<l7;*/
return 0;
} |
Voici le .h :
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
|
using namespace std;
#include <iostream>
#ifndef _Sring
#define _Strng
class String {
private:
char* _string;
public:
String(); //constructeur par défaut
~String(); // destructeur
String(const String &stringACopier);
String& operator=(const char * aString);
String(const char * uneChaine);
operator char*() const;
char *getString();
friend ostream& operator<<(ostream&, String&);
int length();
};
#endif |
Voic mon .cpp :
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 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
|
#include "String.h"
#include <iostream>
using namespace std;
String::String(){
_string = NULL;
}
String::~String(){
delete [] _string;
}
String::String(const String &stringACopier){
if( this != &stringACopier){
_string = new char[strlen(stringACopier._string)+1];
if (_string != NULL){
strcpy (_string, stringACopier._string);
}
}
}
String& String::operator=(const char * aString){
if (_string != NULL){
delete [] _string;
}
_string = new char[strlen(aString)+1];
if (_string != NULL){
strcpy (_string, aString);
}
return (*this);
}
String::String(const char * uneChaine){
_string = new char[strlen(uneChaine)+1];
if (_string != NULL){
strcpy (_string, uneChaine);
}
}
String::operator char*() const
{
char* var;
strcpy (var,_string);
return var;
}
char* String::getString(){
return _string;
}
ostream& operator<< (ostream& flux, String &aString)
{
flux << aString.getString();
return flux;
}
int String::length()
{
int i = 0;
while (_string[i] != '\0')
{
cout << _string[i];
i++;
}
return i;
} |
Je vous remercie d'avance de vos réponse et vous souhaite de joyeuses fêtes.