First publication date: 2020/03/30
1. String
Let's see some basic handling of the string type. In C language, strings are implemented by a char array that ends with the special character '\0'
. In C++, we will use the std::string
class defined in the standard header file string
.
The std::string
class actually implements the C string (that is still available if needed). You could find other string types in the C++ standard library. Some of them can handle different encodinds like UTF-8 where a character is a compound of more than one byte
This page cannot remplace the official documentation but I hope that is more accessible for the first lessons !
1.1. String instanciations
1.2. Basic handling
Reading a stream from the standard input with std::cin >> s
does NOT allow to get something including like a space, tab ....
We have to use getline()
for this :
1.3. Comparison
The usual comparison operators do not work in C but they DO in C++. Have a look:
1.4. Access to a particular character
We can handle a C++ string like a C string. The brackets ([]
operator can be used to access an element even if the string is not an array...
1.5. Concatenation
1.6. How it works
As said in introduction, the C++ string encapsulates the C string.
c_str()
is an accessor to the C array.
1.7. Other operations: insert/erase, replace, substr, find
2. Cast from/to another type
L'astuce pour la conversion est d'utiliser un flux spécifique, un flux chaîne de caractères et non un flux fichier (Les flux fichier sont vus au TP 2).
L'entête à inclure est sstream
.
Pour transformer un entier en chaîne de caractères, il faut utiliser le code suivant :
Pour décryper une valeur donnée par une chaîne de caractères, il faut plutôt faire la chose suivante :
3. Différents types de chaînes de caractères
Si vous allez dans la documentation officielle, vous verrez qu'il y a différents types de chaînes de caractères.
A terme, vous pourez vous poser la question : parmi tous ces types, lesquels sont des chaînes de caractères C++ ?
4. Aller plus loin
Malheureusement, C++ n'est pas aussi complet que Java ou C# sur les manipulations de chaînes de caractères. Nous serons en mesure d'expliquer un peu plus tard comment, par exemple, transformer une chaîne de caractères en majuscules. Si vous ne pouvez pas attendre, attention, ça pique !