C++ Creating String Objects

Creating String Objects

C-string
Array of chars that is null terminated (‘\0’).
C++ – string
Object whose string type is defined in the file
has a large repertoire of functions (e.g. length, replace, etc.)
char cs[ ] = “Napoleon”; // C-string
string s = “Napoleon”; // C++ – string

cout << s << “ has “ << s.length() << “ characters.\n”; s.replace(5, 2,”ia”); //changes s to “Napolian C++ STRING Formatted Input: Stream extraction operator cin >> stringObject;
the extraction operator >> formats the data that it receives through its input stream; it skips over whitespace

Unformatted Input: getline function for a string
getline( cin, s)
does not skip over whitespace
delimited by newline
reads an entire line of characters into s

string s = “ABCDEFG”;
getline(cin, s); //reads entire line of characters into s
char c = s[2]; //assigns ‘C’ to c
S[4] = ‘*’; //changes s to “ABCD*FG”

Not necessarily null terminated
string is not a pointer, but a class
Many member functions take start position and length
If length argument too large, max chosen

LIRE AUSSI :  Cours langage C notions informatiques de base

CREATING STRING OBJECTS

#include
//string initialization

string s; //s contains 0 characters
string s1( « Hello » ); //s1 contains 5 characters
string s2 = “Hello”; //s2 contains 5 characters
//implicitly calls the constructor

string s3( 8, ‘x’ ); //s3 contains 8 ‘x’ characters
string s4 = s3; //s4 contains 8 ‘x’ characters

string s5(s2, 3, 2); //s5 copies a substring of s2; it contains ”lo”

String Objects
C++ strings can be converted to C-strings:
string s = “ABCDEFG”;
const char* cs = s.c_str();
Converts s into the C-string cs.
The c_str() function has a return type const char*

Cours gratuitTélécharger le cours complet

Télécharger aussi :

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *