tete du loic

 Loïc YON [KIUX]

  • Enseignant-chercheur
  • Référent Formation Continue
  • Responsable des contrats pros ingénieur
  • Référent entrepreneuriat
  • Responsable de la filière F2 ingénieur
  • Secouriste Sauveteur du Travail
mail
loic.yon@isima.fr
phone
(+33 / 0) 4 73 40 50 42
location_on
ISIMA
  • twitter
  • linkedin
  • viadeo

[C++] std::string

Lire en Français

First publication date: 2020/03/30

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 !

String instanciations

std::string   s1;
std::string   s2("string 2");
std::string   s3 = "string 3";

Basic handling

  s2 = s3; // assignment
  
  std::cout << s2; // display on the standard output
  std::cin  >> s3; // input from the standard input

  std::cout << (s1.empty()?"empty string":"not empty string");
  
  // Length of strings
  std::cout << s1.length() << std::endl;
  std::cout << s2.size()   << std::endl;

  // Emptying the string
  s3.clear();

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 :

getline(std::cin, s1);

Comparison

The usual comparison operators do not work in C but they DO in C++. Have a look:

  if (s2==s3) std::cout << "strings are equals" ;
  if (s2!=s3) std::cout << "strings are different" ;
  if (s2< s3) std::cout << s2 << " is smaller than " << s3;
  if (s2> s3) std::cout << s2 << " is greater than " << s3;
  if (s2.compare(s3)==0) std::cout << "strings are equals" ;
  if (s3.compare("loic")==0) std::cout << "s3 is identified :-)" ;

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...

  // reading of a character
  std::cout << s2[3];    // 4th character
  std::cout << s2.at(3); // 4th character
  
  // update of a character
  s2[2]    = 'A';
  s2.at(3) = 'B';

Concatenation

  // the two lines do the same
  s2 += s3;
  s2.append(s3);

How it works

As said in introduction, the C++ string encapsulates the C string. c_str() is an accessor to the C array.

std::cout << s2.c_str();
std::cout << (int) s2.c_str()[s2.length()];

Other operations: insert/erase, replace, substr, find

s1.insert(3, s2); // insert s2 to the position 3
s3.erase(0, 4);     // remove the 4th first characters
s3.replace(2,3,s1); // remplace the part of s3 defined between 2 and 5 by the string s1
s = s1.substr(4,2); // extract 2 characters from the given position
unsigned int i = s.find("found", 4); // looks for "found" since the 4th character, returns std::string::npos if not found.

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 :

std::ostringstream oss;
// écrire la valeur dans le flux et tout ce que l'on veut
oss << valeur_entiere;
std::cout << "Résultat" << oss.str();

Pour décryper une valeur donnée par une chaîne de caractères, il faut plutôt faire la chose suivante :

std::istringstream iss(chaine_a_decrypter);
iss >> entier;

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++ ?

std::string s1;
const char * s2;
char * s3;
char s4[256];

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 !

// Exemple tiré de la FAQ C++ de Développez.com

#include <cctype>    // pour tolower et toupper
#include <string>    // pour string
#include <ostream>   // pour cout
#include <algorithm> // pour transform
  
struct my_toupper
{ 
    char operator()(char c) const 
    {
        return std::toupper(static_cast<unsigned char>(c));
    } 
};
 
int main()
{
    std::string s("abcdef");

    std::transform(s.begin(), s.end(), s.begin(), my_toupper());
    std::cout << s; // affiche "ABCDEF"
 
    return 0;
}