basic_string, classebasic_string Class

Les séquences contrôlées par un objet de type basic_string sont la C++ classe de chaîne standard et sont généralement appelées chaînes, mais elles ne doivent pas être confondues avec les chaînes de style C se terminant par un caractère null utilisées dans l’ensemble de la C++ bibliothèque standard.The sequences controlled by an object of type basic_string are the Standard C++ string class and are usually referred to as strings, but they shouldn't be confused with the null-terminated C-style strings used throughout the C++ Standard Library. La chaîne C++ Standard est un conteneur qui permet d’utiliser les chaînes comme types normaux, par exemple pour les opérations de comparaison et de concaténation, les itérateurs, les algorithmes de la bibliothèque C++ Standard, ainsi que les opérations de copie et d’assignation avec la mémoire gérée par la classe allocator.The Standard C++ string is a container that enables the use of strings as normal types, such as comparison and concatenation operations, iterators, C++ Standard Library algorithms, and copying and assigning with class allocator managed memory. Si vous devez convertir une chaîne C++ Standard en chaîne de style C se terminant par un caractère null, utilisez le membre basic_string::c_str.If you need to convert a Standard C++ string to a null-terminated C-style string, use the basic_string::c_str member.

SyntaxeSyntax

template <class CharType, class Traits = char_traits<CharType>, class Allocator = allocator<CharType>>
class basic_string;

ParamètresParameters

CharType CharType
Type de données d'un seul caractère à stocker dans la chaîne.The data type of a single character to be stored in the string. La C++ bibliothèque standard fournit des spécialisations de ce modèle de classe, avec la chaîne des définitions de type pour les éléments de type char, wstring, pour wchar_t, u16string pour char16_tet u32string pour char32_t.The C++ Standard Library provides specializations of this class template, with the type definitions string for elements of type char, wstring, for wchar_t, u16string for char16_t, and u32string for char32_t.

\ traitsTraits</span> Les différentes propriétés importantes des éléments CharType dans une spécialisation basic_string sont décrites par la classe Traits.Various important properties of the CharType elements in a basic_string specialization are described by the class Traits. La valeur par défaut est char_traits< CharType>.The default value is char_traits< CharType>.

\ AllocatorAllocator</span> Type qui représente l'objet allocateur stocké qui contient des informations sur l'allocation et la libération de mémoire de la chaîne.The type that represents the stored allocator object that encapsulates details about the string's allocation and deallocation of memory. La valeur par défaut est allocator< CharType>.The default value is allocator< CharType>.

ConstructeursConstructors

ConstructeurConstructor DescriptionDescription
basic_stringbasic_string Construit une chaîne vide ou initialisée par des caractères spécifiques, ou qui représente une copie complète ou partielle d'un autre objet string ou d'une autre chaîne de style C.Constructs a string that is empty or initialized by specific characters or that is a copy of all or part of some other string object or C-string.

TypedefTypedefs

Nom de typeType name DescriptionDescription
allocator_typeallocator_type Type qui représente la classe allocator d'un objet string.A type that represents the allocator class for a string object.
const_iteratorconst_iterator Type qui fournit un itérateur d’accès aléatoire pouvant accéder à un élément const et le lire dans la chaîne.A type that provides a random-access iterator that can access and read a const element in the string.
const_pointerconst_pointer Type qui fournit un pointeur vers un élément const dans une chaîne.A type that provides a pointer to a const element in a string.
const_referenceconst_reference Type qui fournit une référence à un élément const stocké dans une chaîne pour la lecture et l’exécution des opérations const.A type that provides a reference to a const element stored in a string for reading and performing const operations.
const_reverse_iteratorconst_reverse_iterator Type qui fournit un itérateur d’accès aléatoire pouvant lire tout élément const dans la chaîne.A type that provides a random-access iterator that can read any const element in the string.
difference_typedifference_type Type qui fournit la différence entre deux itérateurs qui font référence aux éléments d'une même chaîne.A type that provides the difference between two iterators that refer to elements within the same string.
iteratoriterator Type qui fournit un itérateur à accès aléatoire pouvant lire ou modifier un élément d'une chaîne.A type that provides a random-access iterator that can read or modify any element in a string.
nposnpos Valeur intégrale non signée initialisée à-1 qui indique « introuvable » ou « tous les caractères restants » quand une fonction de recherche échoue.An unsigned integral value initialized to -1 that indicates either "not found" or "all remaining characters" when a search function fails.
pointerpointer Type qui fournit un pointeur vers un élément caractère d'une chaîne ou d'un tableau de caractères.A type that provides a pointer to a character element in a string or character array.
referencereference Type qui fournit une référence à un élément stocké dans une chaîne.A type that provides a reference to an element stored in a string.
reverse_iteratorreverse_iterator Type qui fournit un itérateur à accès aléatoire pouvant lire ou modifier un élément d'une chaîne inversée.A type that provides a random-access iterator that can read or modify an element in a reversed string.
size_typesize_type Type intégral non signé pour le nombre d'éléments d'une chaîne.An unsigned integral type for the number of elements in a string.
traits_typetraits_type Type pour les caractéristiques de caractère des éléments stockés dans une chaîne.A type for the character traits of the elements stored in a string.
value_typevalue_type Type qui représente le type des caractères stockés dans une chaîne.A type that represents the type of characters stored in a string.

Fonctions membresMember functions

Fonction membreMember function DescriptionDescription
appendappend Ajoute des caractères à la fin d'une chaîne.Adds characters to the end of a string.
assignassign Assigne de nouvelles valeurs de caractère au contenu d'une chaîne.Assigns new character values to the contents of a string.
atat Retourne une référence à l'élément à un emplacement spécifié dans la chaîne.Returns a reference to the element at a specified location in the string.
backback
beginbegin Retourne un itérateur qui traite le premier élément de la chaîne.Returns an iterator addressing the first element in the string.
c_strc_str Convertit le contenu d'une chaîne en chaîne de style C se terminant par un caractère Null.Converts the contents of a string as a C-style, null-terminated, string.
capacitycapacity Retourne le plus grand nombre d'éléments qui peuvent être stockés dans une chaîne sans augmenter l'allocation de mémoire de la chaîne.Returns the largest number of elements that could be stored in a string without increasing the memory allocation of the string.
cbegincbegin Retourne un itérateur const qui traite le premier élément de la chaîne.Returns a const iterator addressing the first element in the string.
cendcend Retourne un itérateur const qui traite l'emplacement situé après le dernier élément d'une chaîne.Returns a const iterator that addresses the location succeeding the last element in a string.
clearclear Efface tous les éléments d'une chaîne.Erases all elements of a string.
comparecompare Compare une chaîne à une chaîne spécifique pour déterminer si les deux chaînes sont équivalentes, ou si l'une est inférieure à l'autre d'un point de vue lexicographique.Compares a string with a specified string to determine if the two strings are equal or if one is lexicographically less than the other.
copycopy Copie tout au plus un nombre spécifique de caractères d'une position indexée dans une chaîne source vers un tableau de caractères cible.Copies at most a specified number of characters from an indexed position in a source string to a target character array. Obsolète.Deprecated. Utilisez basic_string::_Copy_s à la place.Use basic_string::_Copy_s instead.
crbegincrbegin Retourne un itérateur const qui traite le premier élément d'une chaîne inversée.Returns a const iterator that addresses the first element in a reversed string.
crendcrend Retourne un itérateur const qui traite l'emplacement qui suit le dernier élément d'une chaîne inversée.Returns a const iterator that addresses the location succeeding the last element in a reversed string.
_Copy_s_Copy_s Copie tout au plus un nombre spécifique de caractères d'une position indexée dans une chaîne source vers un tableau de caractères cible.Copies at most a specified number of characters from an indexed position in a source string to a target character array.
datadata Convertit le contenu d'une chaîne en tableau de caractères.Converts the contents of a string into an array of characters.
emptyempty Effectue un test pour déterminer si la chaîne contient des caractères.Tests whether the string contains characters.
endend Retourne un itérateur qui traite l'emplacement qui suit le dernier élément d'une chaîne.Returns an iterator that addresses the location succeeding the last element in a string.
eraseerase Supprime un élément ou une plage d'éléments dans une chaîne à partir de l'emplacement spécifié.Removes an element or a range of elements in a string from a specified position.
findfind Recherche une chaîne vers l'avant pour trouver la première occurrence d'une sous-chaîne qui correspond à une séquence spécifique de caractères.Searches a string in a forward direction for the first occurrence of a substring that matches a specified sequence of characters.
find_first_not_offind_first_not_of Recherche dans une chaîne le premier caractère qui n’est pas un élément d’une chaîne spécifiée.Searches through a string for the first character that isn't any element of a specified string.
find_first_offind_first_of Recherche dans une chaîne le premier caractère qui correspond à un élément de la chaîne spécifiée.Searches through a string for the first character that matches any element of a specified string.
find_last_not_offind_last_not_of Recherche dans une chaîne le dernier caractère qui n’est pas un élément d’une chaîne spécifiée.Searches through a string for the last character that isn't any element of a specified string.
find_last_offind_last_of Recherche dans une chaîne le dernier caractère qui est un élément de la chaîne spécifiée.Searches through a string for the last character that is an element of a specified string.
frontfront Retourne une référence au premier élément d'une chaîne.Returns a reference to the first element in a string.
get_allocatorget_allocator Retourne une copie de l'objet allocator utilisé pour construire la chaîne.Returns a copy of the allocator object used to construct the string.
insertinsert Insère un élément, un certain nombre d'éléments ou une plage d'éléments dans la chaîne à la position spécifiée.Inserts an element or a number of elements or a range of elements into the string at a specified position.
lengthlength Retourne le nombre actuel d'éléments contenus dans une chaîne.Returns the current number of elements in a string.
max_sizemax_size Retourne le nombre maximal de caractères qu'une chaîne peut contenir.Returns the maximum number of characters a string could contain.
pop_backpop_back Efface le dernier élément de la chaîne.Erases the last element of the string.
push_backpush_back Ajoute un élément à la fin de la chaîne.Adds an element to the end of the string.
rbeginrbegin Retourne un itérateur au premier élément d'une chaîne inversée.Returns an iterator to the first element in a reversed string.
rendrend Retourne un itérateur qui pointe juste après le dernier élément d'une chaîne inversée.Returns an iterator that points just beyond the last element in a reversed string.
replacereplace Remplace les éléments d'une chaîne à la position spécifiée par des caractères spécifiques ou des caractères copiés à partir d'autres plages, chaînes ou chaînes de style C.Replaces elements in a string at a specified position with specified characters or characters copied from other ranges or strings or C-strings.
reservereserve Définit la capacité de la chaîne en fonction d'un nombre au moins aussi grand que le nombre spécifié.Sets the capacity of the string to a number at least as great as a specified number.
resizeresize Spécifie une nouvelle taille pour une chaîne, en ajoutant ou en effaçant des éléments selon les besoins.Specifies a new size for a string, appending or erasing elements as required.
rfindrfind Recherche une chaîne vers l'arrière pour trouver la première occurrence d'une sous-chaîne qui correspond à une séquence spécifique de caractères.Searches a string in a backward direction for the first occurrence of a substring that matches a specified sequence of characters.
shrink_to_fitshrink_to_fit Ignore la capacité excédentaire de la chaîne.Discards the excess capacity of the string.
sizesize Retourne le nombre actuel d'éléments contenus dans une chaîne.Returns the current number of elements in a string.
substrsubstr Copie une sous-chaîne d'un certain nombre de caractères dans une chaîne qui commence à la position spécifiée.Copies a substring of at most some number of characters from a string beginning from a specified position.
swapswap Échange le contenu de deux chaînes.Exchange the contents of two strings.

OpérateursOperators

opérateurOperator DescriptionDescription
operator+=operator+= Ajoute des caractères à une chaîne.Appends characters to a string.
operator=operator= Assigne de nouvelles valeurs de caractère au contenu d'une chaîne.Assigns new character values to the contents of a string.
operator[]operator[] Fournit une référence au caractère situé à l'index spécifié dans une chaîne.Provides a reference to the character with a specified index in a string.

NotesRemarks

Si une fonction doit générer une séquence supérieure à max_size éléments, la fonction signale une erreur de longueur en levant un objet de type length_error.If a function is asked to generate a sequence longer than max_size elements, the function reports a length error by throwing an object of type length_error.

Les références, pointeurs et itérateurs qui désignent les éléments de la séquence contrôlée peuvent devenir non valides après un appel à une fonction qui modifie la séquence contrôlée, ou après le premier appel à une fonction membre non-const.References, pointers, and iterators that designate elements of the controlled sequence can become invalid after any call to a function that alters the controlled sequence, or after the first call to a non- const member function.

spécificationsRequirements

En-tête : <string>Header: <string>

Espace de noms : stdNamespace: std

basic_string::allocator_typebasic_string::allocator_type

Type qui représente la classe allocator d’un objet string.A type that represents the allocator class for a string object.

typedef Allocator allocator_type;

NotesRemarks

Le type est un synonyme du paramètre de modèle Allocator.The type is a synonym for the template parameter Allocator.

ExempleExample

// basic_string_allocator_type.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;
   // The following lines declare objects
   // that use the default allocator.
   string s1;
   basic_string <char>::allocator_type xchar = s1.get_allocator( );
   // You can now call functions on the allocator class xchar used by s1
}

basic_string::appendbasic_string::append

Ajoute des caractères à la fin d'une chaîne.Adds characters to the end of a string.

basic_string<CharType, Traits, Allocator>& append(
    const value_type* ptr);

basic_string<CharType, Traits, Allocator>& append(
    const value_type* ptr,
    size_type count);

basic_string<CharType, Traits, Allocator>& append(
    const basic_string<CharType, Traits, Allocator>& str,
    size_type offset,
    size_type count);

basic_string<CharType, Traits, Allocator>& append(
    const basic_string<CharType, Traits, Allocator>& str);

basic_string<CharType, Traits, Allocator>& append(
    size_type count,
    value_type char_value);

template <class InputIterator>
basic_string<CharType, Traits, Allocator>& append(
    InputIterator first,
    InputIterator last);

basic_string<CharType, Traits, Allocator>& append(
    const_pointer first,
    const_pointer last);

basic_string<CharType, Traits, Allocator>& append(
    const_iterator first,
    const_iterator last);

ParamètresParameters

\ ptrptr</span> Chaîne C à ajouter.The C-string to be appended.

str str
Chaîne dont les caractères sont à ajouter.The string whose characters are to be appended.

décalageoffset
Index de la partie de la chaîne source fournissant les caractères à ajouter.The index of the part of the source string supplying the characters to be appended.

nombre count
Nombre de caractères à ajouter, au maximum, à partir de la chaîne source.The number of characters to be appended, at most, from the source string.

char_valuechar_value
Valeur du caractère à ajouter.The character value to be appended.

premier first
Itérateur d’entrée qui cible le premier élément de la plage à ajouter.An input iterator addressing the first element in the range to be appended.

dernier last
Itérateur d’entrée, const_pointer ou const_iterator, qui cible la position juste après le dernier élément dans la plage à ajouter.An input iterator, const_pointer, or const_iterator addressing the position of the one beyond the last element in the range to be appended.

Valeur de retourReturn Value

Référence à l’objet string ajouté avec les caractères transmis par la fonction membre.A reference to the string object that is being appended with the characters passed by the member function.

NotesRemarks

Les caractères peuvent être ajoutés à une chaîne à l’aide de l' opérateur + = ou des fonctions membres append ou push_back.Characters may be appended to a string using the operator+= or the member functions append or push_back. operator+= ajoute des valeurs à argument unique tandis que la fonction membre append à plusieurs arguments permet de spécifier une partie spécifique d’une chaîne pour l’ajout de.operator+= appends single-argument values while the multiple-argument append member function allows a specific part of a string to be specified for adding.

ExempleExample

// basic_string_append.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;

   // The first member function
   // appending a C-string to a string
   string str1a ( "Hello " );
   cout << "The original string str1 is: " << str1a << endl;
   const char *cstr1a = "Out There ";
   cout << "The C-string cstr1a is: " << cstr1a << endl;
   str1a.append ( cstr1a );
   cout << "Appending the C-string cstr1a to string str1 gives: "
        << str1a << "." << endl << endl;

   // The second member function
   // appending part of a C-string to a string
   string str1b ( "Hello " );
   cout << "The string str1b is: " << str1b << endl;
   const char *cstr1b = "Out There ";
   cout << "The C-string cstr1b is: " << cstr1b << endl;
   str1b.append ( cstr1b , 3 );
   cout << "Appending the 1st part of the C-string cstr1b "
        << "to string str1 gives: " << str1b << "."
        << endl << endl;

   // The third member function
   // appending part of one string to another
   string str1c ( "Hello " ), str2c ( "Wide World " );
   cout << "The string str2c is: " << str2c << endl;
   str1c.append ( str2c , 5 , 5 );
   cout << "The appended string str1 is: "
        << str1c << "." << endl << endl;

   // The fourth member function
   // appending one string to another in two ways,
   // comparing append and operator [ ]
   string str1d ( "Hello " ), str2d ( "Wide " ), str3d ( "World " );
   cout << "The  string str2d is: " << str2d << endl;
   str1d.append ( str2d );
   cout << "The appended string str1d is: "
        << str1d << "." << endl;
   str1d += str3d;
   cout << "The doubly appended strig str1 is: "
        << str1d << "." << endl << endl;

   // The fifth member function
   // appending characters to a string
   string str1e ( "Hello " );
   str1e.append ( 4 , '!' );
   cout << "The string str1 appended with exclamations is: "
        << str1e << endl << endl;

   // The sixth member function
   // appending a range of one string to another
   string str1f ( "Hello " ), str2f ( "Wide World " );
   cout << "The string str2f is: " << str2f << endl;
   str1f.append ( str2f.begin ( ) + 5 , str2f.end ( ) - 1 );
   cout << "The appended string str1 is: "
        << str1f << "." << endl << endl;
}
The original string str1 is: Hello
The C-string cstr1a is: Out There
Appending the C-string cstr1a to string str1 gives: Hello Out There .

The string str1b is: Hello
The C-string cstr1b is: Out There
Appending the 1st part of the C-string cstr1b to string str1 gives: Hello Out.

The string str2c is: Wide World
The appended string str1 is: Hello World.

The  string str2d is: Wide
The appended string str1d is: Hello Wide .
The doubly appended strig str1 is: Hello Wide World .

The string str1 appended with exclamations is: Hello !!!!

The string str2f is: Wide World
The appended string str1 is: Hello World.

basic_string::assignbasic_string::assign

Assigne de nouvelles valeurs de caractère au contenu d'une chaîne.Assigns new character values to the contents of a string.

basic_string<CharType, Traits, Allocator>& assign(
    const value_type* ptr);

basic_string<CharType, Traits, Allocator>& assign(
    const value_type* ptr,
    size_type count);

basic_string<CharType, Traits, Allocator>& assign(
    const basic_string<CharType, Traits, Allocator>& str,
    size_type off,
    size_type count);

basic_string<CharType, Traits, Allocator>& assign(
    const basic_string<CharType, Traits, Allocator>& str);

basic_string<CharType, Traits, Allocator>& assign(
    size_type count,
    value_type char_value);

template <class InIt>
basic_string<CharType, Traits, Allocator>& assign(
    InputIterator first,
    InputIterator last);

basic_string<CharType, Traits, Allocator>& assign(
    const_pointer first,
    const_pointer last);

basic_string<CharType, Traits, Allocator>& assign(
    const_iterator first,
    const_iterator last);

ParamètresParameters

\ ptrptr</span> Pointeur vers les caractères de la chaîne C à assigner à la chaîne cible.A pointer to the characters of the C-string to be assigned to the target string.

nombre count
Nombre de caractères à assigner, à partir de la chaîne source.The number of characters to be assigned, from the source string.

str str
Chaîne source dont les caractères doivent être assignés à la chaîne cible.The source string whose characters are to be assigned to the target string.

char_valuechar_value
Valeur du caractère à assigner.The character value to be assigned.

premier first
Itérateur d’entrée, const_pointer ou const_iterator, qui cible le premier caractère de la plage de la chaîne source à assigner à la plage cible.An input iterator, const_pointer, or const_iterator addressing the first character in the range of the source string to be assigned to the target range.

dernier last
Itérateur d’entrée, const_pointer ou const_iterator, qui cible la position juste après le dernier caractère de la plage de la chaîne source à assigner à la plage cible.An input iterator, const_pointer, or const_iterator addressing the one beyond the last character in the range of the source string to be assigned to the target range.

désactivé off
Position à laquelle les nouveaux caractères commencent à être assignés.The position at which new characters will start to be assigned.

Valeur de retourReturn Value

Référence à l’objet string auquel la fonction membre assigne les nouveaux caractères.A reference to the string object that is being assigned new characters by the member function.

NotesRemarks

Les chaînes peuvent recevoir de nouvelles valeurs de caractère.The strings can be assigned new character values. La nouvelle valeur peut être une chaîne et une chaîne C, ou un caractère unique.The new value can be either a string and C-string or a single character. L' opérateur = peut être utilisé si la nouvelle valeur peut être décrite par un seul paramètre ; dans le cas contraire, la fonction membre assign, qui a plusieurs paramètres, peut être utilisée pour spécifier la partie de la chaîne qui doit être assignée à une chaîne cible.The operator= may be used if the new value can be described by a single parameter; otherwise the member function assign, which has multiple parameters, can be used to specify which part of the string is to be assigned to a target string.

ExempleExample

// basic_string_assign.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;

   // The first member function assigning the
   // characters of a C-string to a string
   string str1a;
   const char *cstr1a = "Out There";
   cout << "The C-string cstr1a is: " << cstr1a <<  "." << endl;
   str1a.assign ( cstr1a );
   cout << "Assigning the C-string cstr1a to string str1 gives: "
        << str1a << "." << endl << endl;

   // The second member function assigning a specific
   // number of the of characters a C-string to a string
   string  str1b;
   const char *cstr1b = "Out There";
   cout << "The C-string cstr1b is: " << cstr1b << endl;
   str1b.assign ( cstr1b , 3 );
   cout << "Assigning the 1st part of the C-string cstr1b "
        << "to string str1 gives: " << str1b << "."
        << endl << endl;

   // The third member function assigning a specific number
   // of the characters from one string to another string
   string str1c ( "Hello " ), str2c ( "Wide World " );
   cout << "The string str2c is: " << str2c << endl;
   str1c.assign ( str2c , 5 , 5 );
   cout << "The newly assigned string str1 is: "
        << str1c << "." << endl << endl;

   // The fourth member function assigning the characters
   // from one string to another string in two equivalent
   // ways, comparing the assign and operator =
   string str1d ( "Hello" ), str2d ( "Wide" ), str3d ( "World" );
   cout << "The original string str1 is: " << str1d << "." << endl;
   cout << "The string str2d is: " << str2d << endl;
   str1d.assign ( str2d );
   cout << "The string str1 newly assigned with string str2d is: "
        << str1d << "." << endl;
   cout << "The string str3d is: " << str3d << "." << endl;
   str1d = str3d;
   cout << "The string str1 reassigned with string str3d is: "
        << str1d << "." << endl << endl;

   // The fifth member function assigning a specific
   // number of characters of a certain value to a string
   string str1e ( "Hello " );
   str1e.assign ( 4 , '!' );
   cout << "The string str1 assigned with eclamations is: "
        << str1e << endl << endl;

   // The sixth member function assigning the value from
   // the range of one string to another string
   string str1f ( "Hello " ), str2f ( "Wide World " );
   cout << "The string str2f is: " << str2f << endl;
   str1f.assign ( str2f.begin ( ) + 5 , str2f.end ( ) - 1 );
   cout << "The string str1 assigned a range of string str2f is: "
        << str1f << "." << endl << endl;
}
The C-string cstr1a is: Out There.
Assigning the C-string cstr1a to string str1 gives: Out There.

The C-string cstr1b is: Out There
Assigning the 1st part of the C-string cstr1b to string str1 gives: Out.

The string str2c is: Wide World
The newly assigned string str1 is: World.

The original string str1 is: Hello.
The string str2d is: Wide
The string str1 newly assigned with string str2d is: Wide.
The string str3d is: World.
The string str1 reassigned with string str3d is: World.

The string str1 assigned with eclamations is: !!!!

The string str2f is: Wide World
The string str1 assigned a range of string str2f is: World.

basic_string::atbasic_string::at

Fournit une référence au caractère situé à l'index spécifié dans une chaîne.Provides a reference to the character with a specified index in a string.

const_reference at(size_type offset) const;

reference at(size_type offset);

ParamètresParameters

décalageoffset
Index de la position de l’élément à référencer.The index of the position of the element to be referenced.

Valeur de retourReturn Value

Référence au caractère de la chaîne à la position spécifiée par l’index de paramètre.A reference to the character of the string at the position specified by the parameter index.

NotesRemarks

Le premier élément de la chaîne a un index égal à zéro et les éléments suivants sont indexés consécutivement par les entiers positifs, de sorte qu’une chaîne de longueur n a un nième élément indexé par le nombre n- 1.The first element of the string has an index of zero and the following elements are indexed consecutively by the positive integers, so that a string of length n has an nth element indexed by the number n - 1.

L' opérateur[ membre est plus rapide que la fonction membre at pour fournir un accès en lecture et en écriture aux éléments d’une chaîne.The member operator[] is faster than the member function at for providing read and write access to the elements of a string.

Le membre operator[] ne vérifie pas si l’index passé comme paramètre est valide, mais la fonction membre ate et doit donc être utilisée si la validité n’est pas certaine.The member operator[] does not check whether the index passed as a parameter is valid but the member function at does and so should be used if the validity isn't certain. Un index non valide, qui est un index inférieur à zéro ou supérieur ou égal à la taille de la chaîne, passé à la fonction membre at lève une exception de classe out_of_range .An invalid index, which is an index less that zero or greater than or equal to the size of the string, passed to the member function at throws an out_of_range Class exception. Un index non valide passé à operator[] entraîne un comportement indéfini, mais l’index égal à la longueur de la chaîne est un index valide pour les chaînes const, et l’opérateur retourne le caractère null quand il reçoit cet index.An invalid index passed to the operator[] results in undefined behavior, but the index equal to the length of the string is a valid index for const strings and the operator returns the null-character when passed this index.

La référence retournée peut être invalidée par des réallocations ou des modifications de chaîne pour les chaînes non-const.The reference returned may be invalidated by string reallocations or modifications for the non- const strings.

ExempleExample

// basic_string_at.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;
   string str1 ( "Hello world" ), str2 ( "Goodbye world" );
   const string  cstr1 ( "Hello there" ), cstr2 ( "Goodbye now" );
   cout << "The original string str1 is: " << str1 << endl;
   cout << "The original string str2 is: " << str2 << endl;

   // Element access to the non const strings
   basic_string <char>::reference refStr1 = str1 [6];
   basic_string <char>::reference refStr2 = str2.at ( 3 );

   cout << "The character with an index of 6 in string str1 is: "
        << refStr1 << "." << endl;
   cout << "The character with an index of 3 in string str2 is: "
        << refStr2 << "." << endl;

   // Element access to the const strings
   basic_string <char>::const_reference crefStr1 = cstr1 [ cstr1.length ( ) ];
   basic_string <char>::const_reference crefStr2 = cstr2.at ( 8 );

   if ( crefStr1 == '\0' )
      cout << "The null character is returned as a valid reference."
           << endl;
   else
      cout << "The null character is not returned." << endl;
   cout << "The character with index 8 in the const string cstr2 is: "
        << crefStr2 << "." << endl;
}

basic_string::backbasic_string::back

Retourne une référence au dernier élément de la chaîne.Returns a reference to the last element in the string.

const_reference back() const;

reference back();

Valeur de retourReturn Value

Référence au dernier élément de la chaîne, qui doit être non vide.A reference to the last element of the string, which must be non-empty.

NotesRemarks

basic_string::basic_stringbasic_string::basic_string

Construit une chaîne vide, initialisée par des caractères spécifiques ou qui représente une copie complète ou partielle d'un autre objet String ou d'une autre chaîne de style C (non terminée par la valeur null).Constructs a string that is empty, initialized by specific characters, or is a copy of all or part of another string object or C style (null-terminated) string.

basic_string();

explicit basic_string(
    const allocator_type& alloc_type);

basic_string(
    const basic_string& right);

basic_string(
    basic_string&& right);

basic_string(
    const basic_string& right,
    size_type right_offset,
    size_type count = npos);

basic_string(
    const basic_string& right,
    size_type right_offset,
    size_type count,
    const allocator_type& alloc_type);

basic_string(
    const value_type* ptr,
    size_type count);

basic_string(
    const value_type* ptr,
    size_type count,
    const allocator_type& alloc_type);

basic_string(
    const value_type* ptr);

basic_string(
    const value_type* ptr,
    const allocator_type& alloc_type);

basic_string(
    size_type count,
    value_type char_value);

basic_string(
    size_type count,
    value_type char_value,
    const allocator_type& alloc_type);

template <class InputIterator>
basic_string(
    InputIterator first,
    InputIterator last);

template <class InputIterator>
basic_string(
    InputIterator first,
    InputIterator last,
    const allocator_type& alloc_type);

basic_string(
    const_pointer first,
    const_pointer last);

basic_string(
    const_iterator first,
    const_iterator last);

ParamètresParameters

\ ptrptr</span> Chaîne C dont les caractères doivent être utilisés pour initialiser le string en cours de construction.The C-string whose characters are to be used to initialize the string being constructed. Cette valeur ne peut pas être un pointeur null.This value cannot be a null pointer.

alloc_typealloc_type
Classe d'allocateur de stockage pour l'objet String en cours de construction.The storage allocator class for the string object being constructed.

nombre count
Nombre de caractères à initialiser.The number of characters to be initialized.

\ droitright</span> Chaîne pour initialiser la chaîne en cours de construction.The string to initialize the string being constructed.

right_offsetright_offset
Index d'un caractère dans une chaîne qui est le premier à être utilisé pour initialiser les valeurs de caractère de la chaîne en cours de construction.The index of a character in a string that is the first to be used to initialize character values for the string being constructed.

char_valuechar_value
Valeur de caractère à copier dans la chaîne en cours de construction.The character value to be copied into the string being constructed.

premier first
Itérateur d'entrée, const_pointer ou const_iterator qui traite le premier élément dans la plage source à insérer.An input iterator, const_pointer, or const_iterator addressing the first element in the source range to be inserted.

dernier last
Itérateur d'entrée, const_pointer ou const_iterator qui traite la position de l'objet au-delà du dernier élément dans la plage source à insérer.An input iterator, const_pointer, or const_iterator addressing the position of the one beyond the last element in the source range to be inserted.

Valeur de retourReturn Value

Référence à l'objet String qui est construit par les constructeurs.A reference to the string object that is being constructed by the constructors.

NotesRemarks

Tous les constructeurs stockent un basic_string::allocator_type et initialisent la séquence contrôlée.All constructors store an basic_string::allocator_type and initialize the controlled sequence. L'objet allocateur est l'argument al, s'il est présent.The allocator object is the argument al, if present. Pour le constructeur de copie, il s’agit de right.basic_string :: get_allocator().For the copy constructor, it's right.basic_string::get_allocator(). Dans le cas contraire, l’allocateur est Alloc().Otherwise, the allocator is Alloc().

La séquence contrôlée est initialisée avec une copie de la séquence d'opérandes spécifiée par les opérandes restants.The controlled sequence is initialized to a copy of the operand sequence specified by the remaining operands. Un constructeur sans séquence d’opérandes spécifie une séquence contrôlée initiale vide.A constructor without an operand sequence specifies an empty initial controlled sequence. Si InputIterator est un type entier dans un constructeur de modèle, la séquence d’opérande first, last se comporte comme (size_type) first, (value_type) last.If InputIterator is an integer type in a template constructor, the operand sequence first, last behaves the same as (size_type) first, (value_type) last.

ExempleExample

// basic_string_ctor.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;

   // The first member function initializing with a C-string
   const char *cstr1a = "Hello Out There.";
   basic_string <char> str1a ( cstr1a , 5);
   cout << "The string initialized by C-string cstr1a is: "
        << str1a << "." << endl;

   // The second member function initializing with a string
   string  str2a ( "How Do You Do" );
   basic_string <char> str2b ( str2a , 7 , 7 );
   cout << "The string initialized by part of the string cstr2a is: "
        << str2b << "." << endl;

   // The third member function initializing a string
   // with a number of characters of a specific value
   basic_string <char> str3a ( 5, '9' );
   cout << "The string initialized by five number 9s is: "
        << str3a << endl;

   // The fourth member function creates an empty string
   // and string with a specified allocator
   basic_string <char> str4a;
   string str4b;
   basic_string <char> str4c ( str4b.get_allocator( ) );
   if (str4c.empty ( ) )
      cout << "The string str4c is empty." << endl;
   else
      cout << "The string str4c is not empty." << endl;

   // The fifth member function initializes a string from
   // another range of characters
   string str5a ( "Hello World" );
   basic_string <char> str5b ( str5a.begin ( ) + 5 , str5a.end ( ) );
   cout << "The string initialized by another range is: "
        << str5b << "." << endl;
}

basic_string::beginbasic_string::begin

Retourne un itérateur qui traite le premier élément de la chaîne.Returns an iterator addressing the first element in the string.

const_iterator begin() const;

iterator begin();

Valeur de retourReturn Value

Itérateur d’accès aléatoire qui cible le premier élément de la séquence ou la position juste après la fin d’une séquence vide.A random-access iterator that addresses the first element of the sequence or just beyond the end of an empty sequence.

ExempleExample

// basic_string_begin.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( ) {
   using namespace std;
   string str1 ( "No way out." ), str2;
   basic_string <char>::iterator strp_Iter, str1_Iter, str2_Iter;
   basic_string <char>::const_iterator str1_cIter;

   str1_Iter = str1.begin ( );
   cout << "The first character of the string str1 is: "
        << *str1_Iter << endl;
   cout << "The full original string str1 is: " << str1 << endl;

   // The dereferenced iterator can be used to modify a character
*str1_Iter = 'G';
   cout << "The first character of the modified str1 is now: "
        << *str1_Iter << endl;
   cout << "The full modified string str1 is now: " << str1 << endl;

   // The following line would be an error because iterator is const
   // *str1_cIter = 'g';

   // For an empty string, begin is equivalent to end
   if (  str2.begin ( ) == str2.end ( ) )
      cout << "The string str2 is empty." << endl;
   else
      cout << "The string str2 is not empty." << endl;
}

basic_string::c_strbasic_string::c_str

Convertit le contenu d’une chaîne en chaîne de style C se terminant par un caractère null.Converts the contents of a string as a C-style, null-terminated string.

const value_type *c_str() const;

Valeur de retourReturn Value

Pointeur vers la version de style C de la chaîne d’appel.A pointer to the C-style version of the invoking string. La valeur du pointeur n’est pas valide après l’appel d’une fonction non const, y compris le destructeur, dans la classe basic_string de l’objet.The pointer value isn't valid after calling a non-const function, including the destructor, in the basic_string class on the object.

NotesRemarks

Les objets de type chaîne appartenant au modèle de classe basic_string<char > ne sont pas nécessairement terminés par null.Objects of type string belonging to the class template basic_string<char> are not necessarily null terminated. Le caractère null « \0 » est utilisé comme caractère spécial dans une chaîne C pour marquer la fin de la chaîne, mais il n’a aucune signification particulière dans un objet de type chaîne et peut faire partie de la chaîne comme tout autre caractère.The null character ' \0 ' is used as a special character in a C-string to mark the end of the string but has no special meaning in an object of type string and may be a part of the string just like any other character. Il existe une conversion automatique de const char * en chaînes, mais la classe String ne fournit pas de conversion automatique des chaînes de style C en objets de type basic_string<char > .There is an automatic conversion from const char* into strings, but the string class does not provide for automatic conversions from C-style strings to objects of type basic_string<char>.

La chaîne de style C retournée ne doit pas être modifiée, car cela peut invalider le pointeur vers la chaîne, ou supprimé, car la chaîne a une durée de vie limitée et appartient à la chaîne de la classe.The returned C-style string shouldn't be modified, as this could invalidate the pointer to the string, or deleted, as the string has a limited lifetime and is owned by the class string.

ExempleExample

// basic_string_c_str.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;

   string  str1 ( "Hello world" );
   cout << "The original string object str1 is: "
        << str1 << endl;
   cout << "The length of the string object str1 = "
        << str1.length ( ) << endl << endl;

   // Converting a string to an array of characters
   const char *ptr1 = 0;
   ptr1= str1.data ( );
   cout << "The modified string object ptr1 is: " << ptr1
        << endl;
   cout << "The length of character array str1 = "
        << strlen ( ptr1) << endl << endl;

   // Converting a string to a C-style string
   const char *c_str1 = str1.c_str ( );
   cout << "The C-style string c_str1 is: " << c_str1
        << endl;
   cout << "The length of C-style string str1 = "
        << strlen ( c_str1) << endl << endl;
}
The original string object str1 is: Hello world
The length of the string object str1 = 11

The modified string object ptr1 is: Hello world
The length of character array str1 = 11

The C-style string c_str1 is: Hello world
The length of C-style string str1 = 11

basic_string::capacitybasic_string::capacity

Retourne le plus grand nombre d'éléments qui peuvent être stockés dans une chaîne sans augmenter l'allocation de mémoire de la chaîne.Returns the largest number of elements that could be stored in a string without increasing the memory allocation of the string.

size_type capacity() const;

Valeur de retourReturn Value

Taille du stockage actuellement alloué dans la mémoire pour contenir la chaîne.The size of storage currently allocated in memory to hold the string.

NotesRemarks

La fonction membre retourne le stockage actuellement alloué pour contenir la séquence contrôlée, une valeur au moins aussi grande que size.The member function returns the storage currently allocated to hold the controlled sequence, a value at least as large as size.

ExempleExample

// basic_string_capacity.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;
   string  str1 ("Hello world");
   cout << "The original string str1 is: " << str1 << endl;

   // The size and length member functions differ in name only
   basic_string <char>::size_type sizeStr1, lenStr1;
   sizeStr1 = str1.size ( );
   lenStr1 = str1.length ( );

   basic_string <char>::size_type capStr1, max_sizeStr1;
   capStr1 = str1.capacity ( );
   max_sizeStr1 = str1.max_size ( );

   // Compare size, length, capacity & max_size of a string
   cout << "The current size of original string str1 is: "
        << sizeStr1 << "." << endl;
   cout << "The current length of original string str1 is: "
        << lenStr1 << "." << endl;
   cout << "The capacity of original string str1 is: "
        << capStr1 << "." << endl;
   cout << "The max_size of original string str1 is: "
        << max_sizeStr1 << "." << endl << endl;

   str1.erase ( 6, 5 );
   cout << "The modified string str1 is: " << str1 << endl;

   sizeStr1 = str1.size (  );
   lenStr1 = str1.length (  );
   capStr1 = str1.capacity (  );
   max_sizeStr1 = str1.max_size (  );

   // Compare size, length, capacity & max_size of a string
   // after erasing part of the original string
   cout << "The current size of modified string str1 is: "
        << sizeStr1 << "." << endl;
   cout << "The current length of modified string str1 is: "
        << lenStr1 << "." << endl;
   cout << "The capacity of modified string str1 is: "
        << capStr1 << "." << endl;
   cout << "The max_size of modified string str1 is: "
        << max_sizeStr1 << "." << endl;
}

basic_string::cbeginbasic_string::cbegin

Retourne un itérateur const qui traite le premier élément de la plage.Returns a const iterator that addresses the first element in the range.

const_iterator cbegin() const;

Valeur de retourReturn Value

Itérateur const à accès aléatoire qui pointe vers le premier élément de la plage, ou vers l’emplacement situé juste après la fin d’une plage vide (pour une plage vide, cbegin() == cend()).A const random-access iterator that points at the first element of the range, or the location just beyond the end of an empty range (for an empty range, cbegin() == cend()).

NotesRemarks

Avec la valeur de retour cbegin, les éléments de la plage ne peuvent pas être modifiés.With the return value of cbegin, the elements in the range cannot be modified.

Vous pouvez utiliser cette fonction membre à la place de la fonction membre begin() afin de garantir que la valeur de retour est const_iterator.You can use this member function in place of the begin() member function to guarantee that the return value is const_iterator. En général, elle est utilisée conjointement avec le mot clé de déduction de type auto, comme le montre l’exemple suivant.Typically, it's used in conjunction with the auto type deduction keyword, as shown in the following example. Dans l’exemple, considérez Container comme un conteneur modifiable (non const) de tout type qui prend en charge begin() et cbegin().In the example, consider Container to be a modifiable (non- const) container of any kind that supports begin() and cbegin().

auto i1 = Container.begin();
// i1 is Container<T>::iterator
auto i2 = Container.cbegin();

// i2 is Container<T>::const_iterator

basic_string::cendbasic_string::cend

Retourne un itérateur const qui traite l’emplacement juste après le dernier élément d’une plage.Returns a const iterator that addresses the location just beyond the last element in a range.

const_iterator cend() const;

Valeur de retourReturn Value

Itérateur const à accès aléatoire qui pointe juste après la fin de la plage.A const random-access iterator that points just beyond the end of the range.

NotesRemarks

cend est utilisé pour vérifier si un itérateur a dépassé la fin de la plage.cend is used to test whether an iterator has passed the end of its range.

Vous pouvez utiliser cette fonction membre à la place de la fonction membre end() afin de garantir que la valeur de retour est const_iterator.You can use this member function in place of the end() member function to guarantee that the return value is const_iterator. En général, elle est utilisée conjointement avec le mot clé de déduction de type auto, comme le montre l’exemple suivant.Typically, it's used in conjunction with the auto type deduction keyword, as shown in the following example. Dans l’exemple, considérez Container comme un conteneur modifiable (non const) de tout type qui prend en charge end() et cend().In the example, consider Container to be a modifiable (non- const) container of any kind that supports end() and cend().

auto i1 = Container.end();
// i1 is Container<T>::iterator
auto i2 = Container.cend();

// i2 is Container<T>::const_iterator

La valeur retournée par cend ne doit pas être déréférencée.The value returned by cend shouldn't be dereferenced.

basic_string::clearbasic_string::clear

Efface tous les éléments d'une chaîne.Erases all elements of a string.

void clear();

NotesRemarks

La chaîne sur laquelle la fonction membre est appelée est vide.The string on which the member function is called will be empty.

ExempleExample

// basic_string_clear.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;
   string  str1 ("Hello world"), str2;
   basic_string <char>::iterator str_Iter;
   cout << "The original string str1 is: ";
   for ( str_Iter = str1.begin( ); str_Iter != str1.end( ); str_Iter++ )
      cout << *str_Iter;
   cout << endl;

   str1.clear ( );
   cout << "The modified string str1 is: ";
   for ( str_Iter = str1.begin( ); str_Iter != str1.end( ); str_Iter++ )
      cout << *str_Iter;
   cout << endl;

   //For an empty string, begin is equivalent to end
   if ( str1.begin ( ) == str1.end ( ) )
      cout << "Nothing printed above because "
           << "the string str1 is empty." << endl;
   else
      cout << "The string str1 is not empty." << endl;
}
The original string str1 is: Hello world
The modified string str1 is:
Nothing printed above because the string str1 is empty.

basic_string::comparebasic_string::compare

Effectue une comparaison sensible à la casse entre une chaîne et une chaîne spécifiée pour déterminer si les deux chaînes sont équivalentes ou si l’une est inférieure à l’autre d’un point de vue lexicographique.Performs a case sensitive comparison with a specified string to determine if the two strings are equal or if one is lexicographically less than the other.

int compare(
    const basic_string<CharType, Traits, Allocator>& str) const;

int compare(
    size_type position_1,
    size_type number_1,
    const basic_string<CharType, Traits, Allocator>& str) const;

int compare(
    size_type position_1,
    size_type number_1,
    const basic_string<CharType, Traits, Allocator>& str,
    size_type offset,
    size_type count) const;

int compare(
    const value_type* ptr) const;

int compare(
    size_type position_1,
    size_type number_1,
    const value_type* ptr) const;

int compare(
    size_type position_1,
    size_type number_1,
    const value_type* ptr
    size_type number_2) const;

ParamètresParameters

str str
Chaîne à comparer à la chaîne d’opérande.The string that is to be compared to the operand string.

position_1position_1
Index de la chaîne d’opérande à partir duquel commence la comparaison.The index of the operand string at which the comparison begins.

number_1number_1
Nombre maximal de caractères de la chaîne d’opérande à comparer.The maximum number of characters from the operand string to be compared.

number_2number_2
Nombre maximal de caractères de la chaîne de paramètre à comparer.The maximum number of characters from the parameter string to be compared.

décalageoffset
Index de la chaîne de paramètre à partir duquel commence la comparaison.The index of the parameter string at which the comparison begins.

nombre count
Nombre maximal de caractères de la chaîne de paramètre à comparer.The maximum number of characters from the parameter string to be compared.

\ ptrptr</span> Chaîne C à comparer à la chaîne d’opérande.The C-string to be compared to the operand string.

Valeur de retourReturn Value

Valeur négative si la chaîne d’opérande est inférieure à la chaîne de paramètre ; zéro si les deux chaînes sont égales ; ou valeur positive si la chaîne d’opérande est supérieure à la chaîne de paramètre.A negative value if the operand string is less than the parameter string; zero if the two strings are equal; or a positive value if the operand string is greater than the parameter string.

NotesRemarks

Les fonctions membres de compare comparent la totalité ou une partie du paramètre et des chaînes d’opérande en fonction de ce qui est utilisé.The compare member functions compare either all or part of the parameter and operand strings depending on which in used.

La comparaison effectuée respecte la casse.The comparison performed is case sensitive.

ExempleExample

// basic_string_compare.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;

   // The first member function compares
   // an operand string to a parameter string
   int comp1;
   string s1o ( "CAB" );
   string s1p ( "CAB" );
   cout << "The operand string is: " << s1o << endl;
   cout << "The parameter string is: " << s1p << endl;
   comp1 = s1o.compare ( s1p );
   if ( comp1 < 0 )
      cout << "The operand string is less than "
           << "the parameter string." << endl;
   else if ( comp1 == 0 )
      cout << "The operand string is equal to "
           << "the parameter string." << endl;
   else
      cout << "The operand string is greater than "
           << "the parameter string." << endl;
   cout << endl;

   // The second member function compares part of
   // an operand string to a parameter string
   int comp2a, comp2b;
   string s2o ( "AACAB" );
   string s2p ( "CAB" );
   cout << "The operand string is: " << s2o << endl;
   cout << "The parameter string is: " << s2p << endl;
   comp2a = s2o.compare (  2 , 3 , s2p );
   if ( comp2a < 0 )
      cout << "The last three characters of "
           << "the operand string\n are less than "
           << "the parameter string." << endl;
   else if ( comp2a == 0 )
      cout << "The last three characters of "
           << "the operand string\n are equal to "
           << "the parameter string." << endl;
   else
      cout << "The last three characters of "
           << "the operand string\n is greater than "
           << "the parameter string." << endl;

   comp2b = s2o.compare (  0 , 3 , s2p );
   if ( comp2b < 0 )
      cout << "The first three characters of "
           << "the operand string\n are less than "
           << "the parameter string." << endl;
   else if ( comp2b == 0 )
      cout << "The first three characters of "
           << "the operand string\n are equal to "
           << "the parameter string." << endl;
   else
      cout << "The first three characters of "
           << "the operand string\n is greater than "
           << "the parameter string." << endl;
   cout << endl;

   // The third member function compares part of
   // an operand string to part of a parameter string
   int comp3a;
   string s3o ( "AACAB" );
   string s3p ( "DCABD" );
   cout << "The operand string is: " << s3o << endl;
   cout << "The parameter string is: " << s3p << endl;
   comp3a = s3o.compare (  2 , 3 , s3p , 1 , 3 );
   if ( comp3a < 0 )
      cout << "The three characters from position 2 of "
           << "the operand string are less than\n "
           << "the 3 characters parameter string "
           << "from position 1." << endl;
   else if ( comp3a == 0 )
      cout << "The three characters from position 2 of "
           << "the operand string are equal to\n "
           << "the 3 characters parameter string "
           << "from position 1." << endl;
   else
      cout << "The three characters from position 2 of "
           << "the operand string is greater than\n "
           << "the 3 characters parameter string "
           << "from position 1." << endl;
   cout << endl;

   // The fourth member function compares
   // an operand string to a parameter C-string
   int comp4a;
   string s4o ( "ABC" );
   const char* cs4p = "DEF";
   cout << "The operand string is: " << s4o << endl;
   cout << "The parameter C-string is: " << cs4p << endl;
   comp4a = s4o.compare ( cs4p );
   if ( comp4a < 0 )
      cout << "The operand string is less than "
           << "the parameter C-string." << endl;
   else if ( comp4a == 0 )
      cout << "The operand string is equal to "
           << "the parameter C-string." << endl;
   else
      cout << "The operand string is greater than "
           << "the parameter C-string." << endl;
   cout << endl;

   // The fifth member function compares part of
   // an operand string to a parameter C-string
   int comp5a;
   string s5o ( "AACAB" );
   const char* cs5p = "CAB";
   cout << "The operand string is: " << s5o << endl;
   cout << "The parameter string is: " << cs5p << endl;
   comp5a = s5o.compare (  2 , 3 , s2p );
   if ( comp5a < 0 )
      cout << "The last three characters of "
           << "the operand string\n are less than "
           << "the parameter C-string." << endl;
   else if ( comp5a == 0 )
      cout << "The last three characters of "
           << "the operand string\n are equal to "
           << "the parameter C-string." << endl;
   else
      cout << "The last three characters of "
           << "the operand string\n is greater than "
           << "the parameter C-string." << endl;
   cout << endl;

   // The sixth member function compares part of
   // an operand string to part of an equal length of
   // a parameter C-string
   int comp6a;
   string s6o ( "AACAB" );
   const char* cs6p = "ACAB";
   cout << "The operand string is: " << s6o << endl;
   cout << "The parameter C-string is: " << cs6p << endl;
   comp6a = s6o.compare (  1 , 3 , cs6p , 3 );
   if ( comp6a < 0 )
      cout << "The 3 characters from position 1 of "
           << "the operand string are less than\n "
           << "the first 3 characters of the parameter C-string."
           << endl;
   else if ( comp6a == 0 )
      cout << "The 3 characters from position 2 of "
           << "the operand string are equal to\n "
           << "the first 3 characters of the parameter C-string."
           <<  endl;
   else
      cout << "The 3 characters from position 2 of "
           << "the operand string is greater than\n "
           << "the first 3 characters of the parameter C-string."
           << endl;
   cout << endl;
}
The operand string is: CAB
The parameter string is: CAB
The operand string is equal to the parameter string.

The operand string is: AACAB
The parameter string is: CAB
The last three characters of the operand string
are equal to the parameter string.
The first three characters of the operand string
are less than the parameter string.

The operand string is: AACAB
The parameter string is: DCABD
The three characters from position 2 of the operand string are equal to
the 3 characters parameter string from position 1.

The operand string is: ABC
The parameter C-string is: DEF
The operand string is less than the parameter C-string.

The operand string is: AACAB
The parameter string is: CAB
The last three characters of the operand string
are equal to the parameter C-string.

The operand string is: AACAB
The parameter C-string is: ACAB
The 3 characters from position 2 of the operand string are equal to
the first 3 characters of the parameter C-string.

basic_string::const_iteratorbasic_string::const_iterator

Type qui fournit un itérateur d’accès aléatoire pouvant accéder à un élément const et le lire dans la chaîne.A type that provides a random-access iterator that can access and read a const element in the string.

typedef implementation-defined const_iterator;

NotesRemarks

Un type const_iterator ne peut pas être utilisé pour modifier la valeur d’un caractère et est utilisé pour itérer sur une chaîne vers l’avant.A type const_iterator cannot be used to modify the value of a character and is used to iterate through a string in a forward direction.

ExempleExample

Pour savoir comment déclarer et utiliser const_iterator, consultez l’exemple relatif à begin.See the example for begin for an example of how to declare and use const_iterator.

basic_string::const_pointerbasic_string::const_pointer

Type qui fournit un pointeur vers un élément const dans une chaîne.A type that provides a pointer to a const element in a string.

typedef typename allocator_type::const_pointer const_pointer;

NotesRemarks

Le type est un synonyme de allocator_type::const_pointer.The type is a synonym for allocator_type::const_pointer.

Pour le type string, il est équivalent à char*.For type string, it's equivalent to char*.

Les pointeurs déclarés comme const doivent être initialisés au moment de la déclaration.Pointers that are declared const must be initialized when they are declared. Les pointeurs const pointent toujours vers le même emplacement de mémoire et peuvent pointer vers des données constantes ou non-constantes.Const pointers always point to the same memory location and may point to constant or nonconstant data.

ExempleExample

// basic_string_const_ptr.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;
   basic_string<char>::const_pointer pstr1a = "In Here";
   const char *cstr1c = "Out There";

   cout << "The string pstr1a is: " << pstr1a <<  "." << endl;
   cout << "The C-string cstr1c is: " << cstr1c << "." << endl;
}
The string pstr1a is: In Here.
The C-string cstr1c is: Out There.

basic_string::const_referencebasic_string::const_reference

Type qui fournit une référence à un élément const stocké dans une chaîne pour la lecture et l’exécution des opérations const.A type that provides a reference to a const element stored in a string for reading and performing const operations.

typedef typename allocator_type::const_reference const_reference;

NotesRemarks

Un type const_reference ne peut pas être utilisé pour changer la valeur d'un élément.A type const_reference cannot be used to modify the value of an element.

Le type est un synonyme de allocator_type::const_reference.The type is a synonym for allocator_type::const_reference. Pour les typede chaîne, il est équivalent à const char&.For string type, it's equivalent to const char&.

ExempleExample

Pour savoir comment déclarer et utiliser const_reference, consultez l’exemple relatif à at.See the example for at for an example of how to declare and use const_reference.

basic_string::const_reverse_iteratorbasic_string::const_reverse_iterator

Type qui fournit un itérateur d’accès aléatoire pouvant lire tout élément const dans la chaîne.A type that provides a random-access iterator that can read any const element in the string.

typedef std::reverse_iterator<const_iterator> const_reverse_iterator;

NotesRemarks

Un type const_reverse_iterator ne peut pas changer la valeur d’un caractère. Il sert à itérer sur une chaîne dans l’ordre inverse.A type const_reverse_iterator cannot modify the value of a character and is used to iterate through a string in reverse.

ExempleExample

Consultez l’exemple relatif à rbegin pour savoir comment déclarer et utiliser const_reverse_iterator.See the example for rbegin for an example of how to declare and use const_reverse_iterator.

basic_string::copybasic_string::copy

Copie tout au plus un nombre spécifique de caractères d'une position indexée dans une chaîne source vers un tableau de caractères cible.Copies at most a specified number of characters from an indexed position in a source string to a target character array.

Cette méthode est potentiellement dangereuse, car elle suppose que l’appelant vérifie que les valeurs passées sont correctes.This method is potentially unsafe, as it relies on the caller to check that the passed values are correct. Utilisez basic_string::_Copy_s à la place.Consider using basic_string::_Copy_s instead.

size_type copy(
    value_type* ptr,
    size_type count,
    size_type offset = 0) const;

ParamètresParameters

\ ptrptr</span> Tableau de caractères cible dans lequel les éléments doivent être copiés.The target character array to which the elements are to be copied.

nombre Nombre de caractères à copier, au maximum, à partir de la chaîne source.count The number of characters to be copied, at most, from the source string.

décalageoffset
Position de début dans la chaîne source à partir de laquelle les copies doivent être effectuées.The beginning position in the source string from which copies are to be made.

Valeur de retourReturn Value

Nombre de caractères réellement copiés.The number of characters actually copied.

NotesRemarks

Un caractère NULL n’est pas ajouté à la fin de la copie.A null character isn't appended to the end of the copy.

ExempleExample

// basic_string_copy.cpp
// compile with: /EHsc /W3
#include <string>
#include <iostream>

int main( )
{
   using namespace std;
   string str1 ( "Hello World" );
   basic_string <char>::iterator str_Iter;
   char array1 [ 20 ] = { 0 };
   char array2 [ 10 ] = { 0 };
   basic_string <char>:: pointer array1Ptr = array1;
   basic_string <char>:: value_type *array2Ptr = array2;

   cout << "The original string str1 is: ";
   for ( str_Iter = str1.begin( ); str_Iter != str1.end( ); str_Iter++ )
      cout << *str_Iter;
   cout << endl;

   basic_string <char>:: size_type nArray1;
   // Note: string::copy is potentially unsafe, consider
   // using string::_Copy_s instead.
   nArray1 = str1.copy ( array1Ptr , 12 );  // C4996
   cout << "The number of copied characters in array1 is: "
        << nArray1 << endl;
   cout << "The copied characters array1 is: " << array1 << endl;

   basic_string <char>:: size_type nArray2;
   // Note: string::copy is potentially unsafe, consider
   // using string::_Copy_s instead.
   nArray2 = str1.copy ( array2Ptr , 5 , 6  );  // C4996
   cout << "The number of copied characters in array2 is: "
           << nArray2 << endl;
   cout << "The copied characters array2 is: " << array2Ptr << endl;
}
The original string str1 is: Hello World
The number of copied characters in array1 is: 11
The copied characters array1 is: Hello World
The number of copied characters in array2 is: 5
The copied characters array2 is: World

basic_string::crbeginbasic_string::crbegin

Retourne un itérateur const qui traite le premier élément d'une chaîne inversée.Returns a const iterator that addresses the first element in a reversed string.

const_reverse_iterator crbegin() const;

Valeur de retourReturn Value

Itérateur inverse qui pointe juste après la fin de la chaîne.A reverse iterator that points just beyond the end of the string. La position désigne le début de la chaîne inverse.The position designates the beginning of the reverse string.

basic_string::crendbasic_string::crend

Retourne un itérateur const qui traite l'emplacement qui suit le dernier élément d'une chaîne inversée.Returns a const iterator that addresses the location succeeding the last element in a reversed string.

const_reverse_iterator crend() const;

Valeur de retourReturn Value

Itérateur inversé const qui traite l'emplacement qui suit le dernier élément d'une chaîne inversée (emplacement qui précédait celui du premier élément de la chaîne non inversée).A const reverse iterator that addresses the location succeeding the last element in a reversed string (the location that had preceded the first element in the unreversed string).

NotesRemarks

basic_string::_Copy_sbasic_string::_Copy_s

Copie tout au plus un nombre spécifique de caractères d'une position indexée dans une chaîne source vers un tableau de caractères cible.Copies at most a specified number of characters from an indexed position in a source string to a target character array.

size_type _Copy_s(
    value_type* dest,
    size_type dest_size,
    size_type count,
    size_type offset = 0) const;

ParamètresParameters

dest dest
Tableau de caractères cible dans lequel les éléments doivent être copiés.The target character array to which the elements are to be copied.

dest_sizedest_size
La taille de dest.The size of dest.

nombre Nombre de caractères à copier, au maximum, à partir de la chaîne source.count The number of characters to be copied, at most, from the source string.

décalageoffset
Position de début dans la chaîne source à partir de laquelle les copies doivent être effectuées.The beginning position in the source string from which copies are to be made.

Valeur de retourReturn Value

Nombre de caractères réellement copiés.The number of characters actually copied.

NotesRemarks

Un caractère NULL n’est pas ajouté à la fin de la copie.A null character isn't appended to the end of the copy.

ExempleExample

// basic_string__Copy_s.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
    using namespace std;
    string str1("Hello World");
    basic_string<char>::iterator str_Iter;
    const int array1_size = 20;
    char array1[array1_size] = { 0 };
    const int array2_size = 10;
    char array2[array2_size] = { 0 };
    basic_string<char>:: pointer array1Ptr = array1;
    basic_string<char>:: value_type *array2Ptr = array2;

    cout << "The original string str1 is: ";
    for (str_Iter = str1.begin(); str_Iter != str1.end(); str_Iter++)
        cout << *str_Iter;
    cout << endl;

    basic_string<char>::size_type nArray1;
    nArray1 = str1._Copy_s(array1Ptr, array1_size, 12);
    cout << "The number of copied characters in array1 is: "
         << nArray1 << endl;
    cout << "The copied characters array1 is: " << array1 << endl;

    basic_string<char>:: size_type nArray2;
    nArray2 = str1._Copy_s(array2Ptr, array2_size, 5, 6);
    cout << "The number of copied characters in array2 is: "
         << nArray2 << endl;
    cout << "The copied characters array2 is: " << array2Ptr << endl;
}
The original string str1 is: Hello World
The number of copied characters in array1 is: 11
The copied characters array1 is: Hello World
The number of copied characters in array2 is: 5
The copied characters array2 is: World

basic_string::databasic_string::data

Convertit le contenu d’une chaîne en tableau de caractères se terminant par le caractère null.Converts the contents of a string into a null-terminated array of characters.

const value_type *data() const noexcept;
value_type *data() noexcept;

Valeur de retourReturn Value

Pointeur vers le premier élément du tableau terminé par le caractère null qui contient le contenu de la chaîne.A pointer to the first element of the null-terminated array containing the contents of the string. Pour une chaîne vide, le pointeur pointe vers un caractère null unique égal à value_type().For an empty string, the pointer points to a single null character equal to value_type().

NotesRemarks

Le pointeur retourné par data pointe vers une plage valide [data(), data() + size()].The pointer returned by data points at a valid range [data(), data() + size()]. Chaque élément de la plage correspond aux données actuelles de la chaîne.Each element in the range corresponds to the current data in the string. Autrement dit, pour chaque décalage valide n dans la plage, data() + n == addressof(operator[](n)).That is, for every valid offset n in the range, data() + n == addressof(operator[](n)).

Si vous modifiez le contenu de la chaîne retournée par la surcharge const de data, le comportement n’est pas défini.If you modify the contents of the string returned by the const overload of data, the behavior is undefined. Vous bénéficiez également d’un comportement indéfini si le caractère null du terminal est remplacé par une autre valeur.You also get undefined behavior if the terminal null character is changed to any other value. Le pointeur retourné peut être invalidé si une référence non const à la chaîne est passée à une fonction de bibliothèque standard.The returned pointer may be invalidated if a non-const reference to the string is passed to a standard library function. Elle peut également être invalidée par un appel à une fonction membre non const.It can also be invalidated by a call to a non-const member function. Les appels aux membres at, back, begin, end, front, rbegin, rendet operator[] n’invalident pas le pointeur.Calls to members at, back, begin, end, front, rbegin, rend, and operator[] don't invalidate the pointer.

Avant C++ 11, data n’avait pas garanti que la chaîne retournée était terminée par un caractère null.Prior to C++11, data didn't guarantee the returned string was null-terminated. Depuis C++ 11, data et c_str retournent toutes deux une chaîne terminée par le caractère null, et sont effectivement identiques.Since C++11, data and c_str both return a null-terminated string, and are effectively the same.

La surcharge non const est une nouveauté dans C++ 17.The non-const overload is new in C++17. Pour l’utiliser, spécifiez l’option de compilateur /std : c++ 17 ou /std : c + + latest .To use it, specify the /std:c++17 or /std:c++latest compiler option.

ExempleExample

// basic_string_data.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;

   string str1 ( "Hello world" );
   cout << "The original string object str1 is: "
        << str1 << endl;
   cout << "The length of the string object str1 = "
        << str1.length ( ) << endl << endl;

   // Converting a string to an array of characters
   const char *ptr1 = 0;
   ptr1= str1.data ( );
   cout << "The modified string object ptr1 is: " << ptr1
        << endl;
   cout << "The length of character array str1 = "
        << strlen ( ptr1) << endl << endl;

   // Converting a string to a C-style string
   const char *c_str1 = str1.c_str ( );
   cout << "The C-style string c_str1 is: " << c_str1
        << endl;
   cout << "The length of C-style string str1 = "
        << strlen ( c_str1) << endl << endl;
}
The original string object str1 is: Hello world
The length of the string object str1 = 11

The modified string object ptr1 is: Hello world
The length of character array str1 = 11

The C-style string c_str1 is: Hello world
The length of C-style string str1 = 11

basic_string::difference_typebasic_string::difference_type

Type qui fournit la différence entre deux itérateurs qui font référence aux éléments d'une même chaîne.A type that provides the difference between two iterators that refer to elements within the same string.

typedef typename allocator_type::difference_type difference_type;

NotesRemarks

Le type d'entier signé décrit un objet qui peut représenter la différence entre les adresses de deux éléments quelconques dans la séquence contrôlée.The signed integer type describes an object that can represent the difference between the addresses of any two elements in the controlled sequence.

Pour le type string, il est équivalent à ptrdiff_t.For type string, it's equivalent to ptrdiff_t.

ExempleExample

// basic_string_diff_type.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;
   string str1 ( "quintillion" );
   cout << "The original string str1 is: " << str1 << endl;
   basic_string <char>::size_type indexChFi, indexChLi;

   indexChFi = str1.find_first_of ( "i" );
   indexChLi = str1.find_last_of ( "i" );
   basic_string<char>::difference_type diffi = indexChLi - indexChFi;

   cout << "The first character i is at position: "
        << indexChFi << "." << endl;
   cout << "The last character i is at position: "
        << indexChLi << "." << endl;
   cout << "The difference is: " << diffi << "." << endl;
}
The original string str1 is: quintillion
The first character i is at position: 2.
The last character i is at position: 8.
The difference is: 6.

basic_string::emptybasic_string::empty

Vérifie si la chaîne contient ou non des caractères.Tests whether the string contains characters or not.

bool empty() const;

Valeur de retourReturn Value

true si l’objet de chaîne ne contient aucun caractère ; false s’il a au moins un caractère.true if the string object contains no characters; false if it has at least one character.

NotesRemarks

La fonction membre est équivalente à size == 0.The member function is equivalent to size == 0.

ExempleExample

// basic_string_empty.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main() {
   using namespace std;

   bool b1, b2;

   string str1 ("Hello world");
   cout << "The original string object str1 is: " << str1 << endl;
   b1 = str1.empty();
   if (b1)
      cout << "The string object str1 is empty." << endl;
   else
      cout << "The string object str1 is not empty." << endl;
   cout << endl;

   // An example of an empty string object
   string str2;
   b2 = str2.empty();
   if (b2)
      cout << "The string object str2 is empty." << endl;
   else
      cout << "The string object str2 is not empty." << endl;
}

basic_string::endbasic_string::end

Retourne un itérateur qui traite l'emplacement qui suit le dernier élément d'une chaîne.Returns an iterator that addresses the location succeeding the last element in a string.

const_iterator end() const;

iterator end();

Valeur de retourReturn Value

Retourne un itérateur d’accès aléatoire qui cible l’emplacement situé après le dernier élément d’une chaîne.Returns a random-access iterator that addresses the location succeeding the last element in a string.

NotesRemarks

end est souvent utilisé pour tester si un itérateur a atteint la fin de sa chaîne.end is often used to test whether an iterator has reached the end of its string. La valeur retournée par end ne doit pas être déréférencée.The value returned by end shouldn't be dereferenced.

Si la valeur de retour de end est assignée à un const_iterator, l’objet de chaîne ne peut pas être modifié.If the return value of end is assigned to a const_iterator, the string object cannot be modified. Si la valeur de retour de end est assignée à un iterator, l’objet String peut être modifié.If the return value of end is assigned to an iterator, the string object can be modified.

ExempleExample

// basic_string_end.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;
   string str1 ( "No way out." ), str2;
   basic_string <char>::iterator str_Iter, str1_Iter, str2_Iter;
   basic_string <char>::const_iterator str1_cIter;

   str1_Iter = str1.end ( );
   str1_Iter--;
   str1_Iter--;
   cout << "The last character-letter of the string str1 is: " << *str1_Iter << endl;
   cout << "The full orginal string str1 is: " << str1 << endl;

   // end used to test when an iterator has reached the end of its string
   cout << "The string is now: ";
   for ( str_Iter = str1.begin( ); str_Iter != str1.end( ); str_Iter++ )
      cout << *str_Iter;
   cout << endl;

   // The dereferenced iterator can be used to modify a character
*str1_Iter = 'T';
   cout << "The last character-letter of the modified str1 is now: "
        << *str1_Iter << endl;
   cout << "The modified string str1 is now: " << str1 << endl;

   // The following line would be an error because iterator is const
   // *str1_cIter = 'T';

   // For an empty string, end is equivalent to begin
   if ( str2.begin( ) == str2.end ( ) )
      cout << "The string str2 is empty." << endl;
   else
      cout << "The stringstr2  is not empty." << endl;
}
The last character-letter of the string str1 is: t
The full orginal string str1 is: No way out.
The string is now: No way out.
The last character-letter of the modified str1 is now: T
The modified string str1 is now: No way ouT.
The string str2 is empty.

basic_string::erasebasic_string::erase

Supprime un élément ou une plage d'éléments dans une chaîne à partir de l'emplacement spécifié.Removes an element or a range of elements in a string from a specified position.

iterator erase(
    iterator first,
    iterator last);

iterator erase(
    iterator iter);

basic_string<CharType, Traits, Allocator>& erase(
    size_type offset = 0,
    size_type count = npos);

ParamètresParameters

premier first
Itérateur qui cible la position du premier élément de la plage à effacer.An iterator addressing the position of the first element in the range to be erased.

dernier last
Itérateur qui cible la position juste après le dernier élément de la plage à effacer.An iterator addressing the position one past the last element in the range to be erased.

iteriter
Itérateur qui cible la position de l’élément de la chaîne à effacer.An iterator addressing the position of the element in the string to be erased.

décalageoffset
Index du premier caractère de la chaîne à supprimer.The index of the first character in the string to be removed.

nombre count
Nombre d’éléments qui seront supprimés s’il y en a autant dans la plage de la chaîne commençant par offset.The number of elements that will be removed if there are as many in the range of the string beginning with offset.

Valeur de retourReturn Value

Pour les deux premières fonctions membres, un itérateur qui cible le premier caractère après le dernier caractère supprimé par la fonction membre.For the first two member functions, an iterator addressing the first character after the last character removed by the member function. Pour la troisième fonction membre, une référence à l’objet de chaîne à partir duquel les éléments ont été effacés.For the third member function, a reference to the string object from which the elements have been erased.

NotesRemarks

La troisième fonction membre retourne *this.The third member function returns *this.

ExempleExample

// basic_string_erase.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;

   // The 1st member function using a range demarcated
   // by iterators
   string str1 ( "Hello world" );
   basic_string <char>::iterator str1_Iter;
   cout << "The original string object str1 is: "
        << str1 << "." << endl;
   str1_Iter = str1.erase ( str1.begin ( ) + 3 , str1.end ( ) - 1 );
   cout << "The first element after those removed is: "
        << *str1_Iter << "." << endl;
   cout << "The modified string object str1 is: " << str1
           << "." << endl << endl;

   // The 2nd member function erasing a char pointed to
   // by an iterator
   string str2 ( "Hello World" );
   basic_string <char>::iterator str2_Iter;
   cout << "The original string object str2 is: " << str2
        << "." << endl;
   str2_Iter = str2.erase ( str2.begin ( ) + 5 );
   cout << "The first element after those removed is: "
        << *str2_Iter << "." << endl;
   cout << "The modified string object str2 is: " << str2
        << "." << endl << endl;

   // The 3rd member function erasing a number of chars
   // after a char
   string str3 ( "Hello computer" ), str3m;
   basic_string <char>::iterator str3_Iter;
   cout << "The original string object str3 is: "
        << str3 << "." << endl;
   str3m = str3.erase ( 6 , 8 );
   cout << "The modified string object str3m is: "
        << str3m << "." << endl;
}
The original string object str1 is: Hello world.
The first element after those removed is: d.
The modified string object str1 is: Held.

The original string object str2 is: Hello World.
The first element after those removed is: W.
The modified string object str2 is: HelloWorld.

The original string object str3 is: Hello computer.
The modified string object str3m is: Hello .

basic_string::findbasic_string::find

Recherche une chaîne vers l'avant pour trouver la première occurrence d'une sous-chaîne qui correspond à une séquence spécifique de caractères.Searches a string in a forward direction for the first occurrence of a substring that matches a specified sequence of characters.

size_type find(
    value_type char_value,
    size_type offset = 0) const;

size_type find(
    const value_type* ptr,
    size_type offset = 0) const;

size_type find(
    const value_type* ptr,
    size_type offset,
    size_type count) const;

size_type find(
    const basic_string<CharType, Traits, Allocator>& str,
    size_type offset = 0) const;

ParamètresParameters

char_valuechar_value
Valeur de caractère que la fonction membre doit rechercher.The character value for which the member function is to search.

décalageoffset
Index de la position à laquelle la recherche doit commencer.Index of the position at which the search is to begin.

\ ptrptr</span> C-string que la fonction membre doit rechercher.The C-string for which the member function is to search.

nombre count
Nombre de caractères, en comptant à partir du premier caractère, dans le C-string que la fonction membre doit rechercher.The number of characters, counting forward from the first character, in the C-string for which the member function is to search.

str str
Chaîne que la fonction membre doit rechercher.The string for which the member function is to search.

Valeur de retourReturn Value

Index du premier caractère de la sous-chaîne recherchée en cas de succès ; dans le cas contraire, npos.The index of the first character of the substring searched for when successful; otherwise npos.

ExempleExample

// basic_string_find.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;

   // The first member function
   // searches for a single character in a string
   string str1 ( "Hello Everyone" );
   cout << "The original string str1 is: " << str1 << endl;
   basic_string <char>::size_type indexCh1a, indexCh1b;

   indexCh1a = str1.find ( "e" , 3 );
   if (indexCh1a != string::npos )
      cout << "The index of the 1st 'e' found after the 3rd"
           << " position in str1 is: " << indexCh1a << endl;
   else
      cout << "The character 'e' was not found in str1 ." << endl;

   indexCh1b = str1.find ( "x" );
   if (indexCh1b != string::npos )
      cout << "The index of the 'x' found in str1 is: "
           << indexCh1b << endl << endl;
   else
      cout << "The Character 'x' was not found in str1."
           << endl << endl;

   // The second member function searches a string
   // for a substring as specified by a C-string
   string str2 ( "Let me make this perfectly clear." );
   cout << "The original string str2 is: " << str2 << endl;
   basic_string <char>::size_type indexCh2a, indexCh2b;

   const char *cstr2 = "perfect";
   indexCh2a = str2.find ( cstr2 , 5 );
   if ( indexCh2a != string::npos )
      cout << "The index of the 1st element of 'perfect' "
           << "after\n the 5th position in str2 is: "
           << indexCh2a << endl;
   else
      cout << "The substring 'perfect' was not found in str2 ."
           << endl;

   const char *cstr2b = "imperfectly";
   indexCh2b = str2.find ( cstr2b , 0 );
   if (indexCh2b != string::npos )
      cout << "The index of the 1st element of 'imperfect' "
           << "after\n the 5th position in str3 is: "
           << indexCh2b << endl;
   else
      cout << "The substring 'imperfect' was not found in str2 ."
           << endl << endl;

   // The third member function searches a string
   // for a substring as specified by a C-string
   string str3 ( "This is a sample string for this program" );
   cout << "The original string str3 is: " << str3 << endl;
   basic_string <char>::size_type indexCh3a, indexCh3b;

   const char *cstr3a = "sample";
   indexCh3a = str3.find ( cstr3a );
   if ( indexCh3a != string::npos )
      cout << "The index of the 1st element of sample "
           << "in str3 is: " << indexCh3a << endl;
   else
      cout << "The substring 'perfect' was not found in str3 ."
           << endl;

   const char *cstr3b = "for";
   indexCh3b = str3.find ( cstr3b , indexCh3a + 1 , 2 );
   if (indexCh3b != string::npos )
      cout << "The index of the next occurrence of 'for' is in "
           << "str3 begins at: " << indexCh3b << endl << endl;
   else
      cout << "There is no next occurrence of 'for' in str3 ."
           << endl << endl;

   // The fourth member function searches a string
   // for a substring as specified by a string
   string str4 ( "clearly this perfectly unclear." );
   cout << "The original string str4 is: " << str4 << endl;
   basic_string <char>::size_type indexCh4a, indexCh4b;

   string str4a ( "clear" );
   indexCh4a = str4.find ( str4a , 5 );
   if ( indexCh4a != string::npos )
      cout << "The index of the 1st element of 'clear' "
           << "after\n the 5th position in str4 is: "
           << indexCh4a << endl;
   else
      cout << "The substring 'clear' was not found in str4 ."
           << endl;

   string str4b ( "clear" );
   indexCh4b = str4.find ( str4b );
   if (indexCh4b != string::npos )
      cout << "The index of the 1st element of 'clear' "
           << "in str4 is: "
           << indexCh4b << endl;
   else
      cout << "The substring 'clear' was not found in str4 ."
           << endl << endl;
}
The original string str1 is: Hello Everyone
The index of the 1st 'e' found after the 3rd position in str1 is: 8
The Character 'x' was not found in str1.

The original string str2 is: Let me make this perfectly clear.
The index of the 1st element of 'perfect' after
the 5th position in str2 is: 17
The substring 'imperfect' was not found in str2 .

The original string str3 is: This is a sample string for this program
The index of the 1st element of sample in str3 is: 10
The index of the next occurrence of 'for' is in str3 begins at: 24

The original string str4 is: clearly this perfectly unclear.
The index of the 1st element of 'clear' after
the 5th position in str4 is: 25
The index of the 1st element of 'clear' in str4 is: 0

basic_string::find_first_not_ofbasic_string::find_first_not_of

Recherche dans une chaîne le premier caractère qui n’est pas un élément d’une chaîne spécifiée.Searches through a string for the first character that isn't an element of a specified string.

size_type find_first_not_of(
    value_type char_value,
    size_type offset = 0) const;

size_type find_first_not_of(
    const value_type* ptr,
    size_type offset = 0) const;

size_type find_first_not_of(
    const value_type* ptr,
    size_type offset,
    size_type count) const;

size_type find_first_not_of(
    const basic_string<CharType, Traits, Allocator>& str,
    size_type offset = 0) const;

ParamètresParameters

char_valuechar_value
Valeur de caractère que la fonction membre doit rechercher.The character value for which the member function is to search.

décalageoffset
Index de la position à laquelle la recherche doit commencer.Index of the position at which the search is to begin.

\ ptrptr</span> C-string que la fonction membre doit rechercher.The C-string for which the member function is to search.

nombre count
Nombre de caractères, en comptant à partir du premier caractère, dans le C-string que la fonction membre doit rechercher.The number of characters, counting forward from the first character, in the C-string for which the member function is to search.

str str
Chaîne que la fonction membre doit rechercher.The string for which the member function is to search.

Valeur de retourReturn Value

Index du premier caractère de la sous-chaîne recherchée en cas de succès ; dans le cas contraire, npos.The index of the first character of the substring searched for when successful; otherwise npos.

ExempleExample

// basic_string_find_first_not_of.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;

   // The first member function
   // searches for a single character in a string
   string str1 ( "xddd-1234-abcd" );
   cout << "The original string str1 is: " << str1 << endl;
   basic_string <char>::size_type indexCh1a, indexCh1b;
   static const basic_string <char>::size_type npos = -1;

   indexCh1a = str1.find_first_not_of ( "d" , 2 );
   if ( indexCh1a != npos )
      cout << "The index of the 1st 'd' found after the 3rd"
           << " position in str1 is: " << indexCh1a << endl;
   else
      cout << "The character 'd' was not found in str1 ." << endl;

   indexCh1b = str1.find_first_not_of  ( "x" );
   if (indexCh1b != npos )
      cout << "The index of the 'non x' found in str1 is: "
           << indexCh1b << endl << endl;
   else
      cout << "The character 'non x' was not found in str1."
           << endl << endl;

   // The second member function searches a string
   // for a substring as specified by a C-string
   string str2 ( "BBB-1111" );
   cout << "The original string str2 is: " << str2 << endl;
   basic_string <char>::size_type indexCh2a, indexCh2b;

   const char *cstr2 = "B1";
   indexCh2a = str2.find_first_not_of ( cstr2 , 6 );
   if ( indexCh2a != npos )
      cout << "The index of the 1st occurrence of an "
           << "element of 'B1' in str2 after\n the 6th "
           << "position is: " << indexCh2a << endl;
   else
      cout << "Elements of the substring 'B1' were not"
           << "\n found in str2 after the 6th position."
           << endl;

   const char *cstr2b = "B2";
   indexCh2b = str2.find_first_not_of ( cstr2b );
   if ( indexCh2b != npos )
      cout << "The index of the 1st element of 'B2' "
           << "after\n the 0th position in str2 is: "
           << indexCh2b << endl << endl;
   else
      cout << "The substring 'B2' was not found in str2 ."
           << endl << endl << endl;

   // The third member function searches a string
   // for a substring as specified by a C-string
   string str3 ( "444-555-GGG" );
   cout << "The original string str3 is: " << str3 << endl;
   basic_string <char>::size_type indexCh3a, indexCh3b;

   const char *cstr3a = "45G";
   indexCh3a = str3.find_first_not_of ( cstr3a );
   if ( indexCh3a != npos )
      cout << "The index of the 1st occurrence of an "
           << "element in str3\n other than one of the "
           << "characters in '45G' is: " << indexCh3a
           << endl;
   else
      cout << "Elements in str3 contain only characters "
           << " in the string '45G'. "
           << endl;

   const char *cstr3b = "45G";
   indexCh3b = str3.find_first_not_of ( cstr3b , indexCh3a + 1 , 2 );
   if ( indexCh3b != npos )
      cout << "The index of the second occurrence of an "
           << "element of '45G' in str3\n after the 0th "
           << "position is: " << indexCh3b << endl << endl;
   else
      cout << "Elements in str3 contain only characters "
           << " in the string  '45G'. "
           << endl  << endl;

   // The fourth member function searches a string
   // for a substring as specified by a string
   string str4 ( "12-ab-12-ab" );
   cout << "The original string str4 is: " << str4 << endl;
   basic_string <char>::size_type indexCh4a, indexCh4b;

   string str4a ( "ba3" );
   indexCh4a = str4.find_first_not_of ( str4a , 5 );
   if (indexCh4a != npos )
      cout << "The index of the 1st non occurrence of an "
           << "element of 'ba3' in str4 after\n the 5th "
           << "position is: " << indexCh4a << endl;
   else
      cout << "Elements other than those in the substring"
           << " 'ba3' were not found in the string str4."
           << endl;

   string str4b ( "12" );
   indexCh4b = str4.find_first_not_of ( str4b  );
   if (indexCh4b != npos )
      cout << "The index of the 1st non occurrence of an "
           << "element of '12' in str4 after\n the 0th "
           << "position is: " << indexCh4b << endl;
   else
      cout << "Elements other than those in the substring"
           << " '12' were not found in the string str4."
           << endl;
}
The original string str1 is: xddd-1234-abcd
The index of the 1st 'd' found after the 3rd position in str1 is: 4
The index of the 'non x' found in str1 is: 1

The original string str2 is: BBB-1111
Elements of the substring 'B1' were not
found in str2 after the 6th position.
The index of the 1st element of 'B2' after
the 0th position in str2 is: 3

The original string str3 is: 444-555-GGG
The index of the 1st occurrence of an element in str3
other than one of the characters in '45G' is: 3
The index of the second occurrence of an element of '45G' in str3
after the 0th position is: 7

The original string str4 is: 12-ab-12-ab
The index of the 1st non occurrence of an element of 'ba3' in str4 after
the 5th position is: 5
The index of the 1st non occurrence of an element of '12' in str4 after
the 0th position is: 2

basic_string::find_first_ofbasic_string::find_first_of

Recherche dans une chaîne le premier caractère qui correspond à un élément de la chaîne spécifiée.Searches through a string for the first character that matches any element of a specified string.

size_type find_first_of(
    value_type char_value,
    size_type offset = 0) const;

size_type find_first_of(
    const value_type* ptr,
    size_type offset = 0) const;

size_type find_first_of(
    const value_type* ptr,
    size_type offset,
    size_type count) const;

size_type find_first_of(
    const basic_string<CharType, Traits, Allocator>& str,
    size_type offset = 0) const;

ParamètresParameters

char_valuechar_value
Valeur de caractère que la fonction membre doit rechercher.The character value for which the member function is to search.

décalageoffset
Index de la position à laquelle la recherche doit commencer.Index of the position at which the search is to begin.

\ ptrptr</span> C-string que la fonction membre doit rechercher.The C-string for which the member function is to search.

nombre count
Nombre de caractères, en comptant à partir du premier caractère, dans le C-string que la fonction membre doit rechercher.The number of characters, counting forward from the first character, in the C-string for which the member function is to search.

str str
Chaîne que la fonction membre doit rechercher.The string for which the member function is to search.

Valeur de retourReturn Value

Index du premier caractère de la sous-chaîne recherchée en cas de succès ; dans le cas contraire, npos.The index of the first character of the substring searched for when successful; otherwise npos.

ExempleExample

// basic_string_find_first_of.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;

   // The first member function
   // searches for a single character in a string
   string str1 ( "abcd-1234-abcd-1234" );
   cout << "The original string str1 is: " << str1 << endl;
   basic_string <char>::size_type indexCh1a, indexCh1b;
   static const basic_string <char>::size_type npos = -1;

   indexCh1a = str1.find_first_of ( "d" , 5 );
   if ( indexCh1a != npos )
      cout << "The index of the 1st 'd' found after the 5th"
           << " position in str1 is: " << indexCh1a << endl;
   else
      cout << "The character 'd' was not found in str1 ." << endl;

   indexCh1b = str1.find_first_of ( "x" );
   if ( indexCh1b != npos )
      cout << "The index of the 'x' found in str1 is: "
           << indexCh1b << endl << endl;
   else
      cout << "The character 'x' was not found in str1."
           << endl << endl;

   // The second member function searches a string
   // for any element of a substring as specified by a C-string
   string str2 ( "ABCD-1234-ABCD-1234" );
   cout << "The original string str2 is: " << str2 << endl;
   basic_string <char>::size_type indexCh2a, indexCh2b;

   const char *cstr2 = "B1";
   indexCh2a = str2.find_first_of ( cstr2 , 6 );
   if ( indexCh2a != npos )
      cout << "The index of the 1st occurrence of an "
           << "element of 'B1' in str2 after\n the 6th "
           << "position is: " << indexCh2a << endl;
   else
      cout << "Elements of the substring 'B1' were not "
           << "found in str2 after the 10th position."
           << endl;

   const char *cstr2b = "D2";
   indexCh2b = str2.find_first_of ( cstr2b );
   if ( indexCh2b != npos )
      cout << "The index of the 1st element of 'D2' "
           << "after\n the 0th position in str2 is: "
           << indexCh2b << endl << endl;
   else
      cout << "The substring 'D2' was not found in str2 ."
           << endl << endl << endl;

   // The third member function searches a string
   // for any element of a substring as specified by a C-string
   string str3 ( "123-abc-123-abc-456-EFG-456-EFG" );
   cout << "The original string str3 is: " << str3 << endl;
   basic_string <char>::size_type indexCh3a, indexCh3b;

   const char *cstr3a = "5G";
   indexCh3a = str3.find_first_of ( cstr3a );
   if ( indexCh3a != npos )
      cout << "The index of the 1st occurrence of an "
           << "element of '5G' in str3 after\n the 0th "
           << "position is: " << indexCh3a << endl;
   else
      cout << "Elements of the substring '5G' were not "
           << "found in str3\n after the 0th position."
           << endl;

   const char *cstr3b = "5GF";
   indexCh3b = str3.find_first_of  ( cstr3b , indexCh3a + 1 , 2 );
   if (indexCh3b != npos )
      cout << "The index of the second occurrence of an "
           << "element of '5G' in str3\n after the 0th "
           << "position is: " << indexCh3b << endl << endl;
   else
      cout << "Elements of the substring '5G' were not "
           << "found in str3\n after the first occurrrence."
           << endl << endl;

   // The fourth member function searches a string
   // for any element of a substring as specified by a string
   string str4 ( "12-ab-12-ab" );
   cout << "The original string str4 is: " << str4 << endl;
   basic_string <char>::size_type indexCh4a, indexCh4b;

   string str4a ( "ba3" );
   indexCh4a = str4.find_first_of ( str4a , 5 );
   if ( indexCh4a != npos )
      cout << "The index of the 1st occurrence of an "
           << "element of 'ba3' in str4 after\n the 5th "
           << "position is: " << indexCh4a << endl;
   else
      cout << "Elements of the substring 'ba3' were not "
           << "found in str4\n after the 0th position."
           << endl;

   string str4b ( "a2" );
   indexCh4b = str4.find_first_of ( str4b );
   if ( indexCh4b != npos )
      cout << "The index of the 1st occurrence of an "
           << "element of 'a2' in str4 after\n the 0th "
           << "position is: " << indexCh4b << endl;
   else
      cout << "Elements of the substring 'a2' were not "
           << "found in str4\n after the 0th position."
           << endl;
}
The original string str1 is: abcd-1234-abcd-1234
The index of the 1st 'd' found after the 5th position in str1 is: 13
The character 'x' was not found in str1.

The original string str2 is: ABCD-1234-ABCD-1234
The index of the 1st occurrence of an element of 'B1' in str2 after
the 6th position is: 11
The index of the 1st element of 'D2' after
the 0th position in str2 is: 3

The original string str3 is: 123-abc-123-abc-456-EFG-456-EFG
The index of the 1st occurrence of an element of '5G' in str3 after
the 0th position is: 17
The index of the second occurrence of an element of '5G' in str3
after the 0th position is: 22

The original string str4 is: 12-ab-12-ab
The index of the 1st occurrence of an element of 'ba3' in str4 after
the 5th position is: 9
The index of the 1st occurrence of an element of 'a2' in str4 after
the 0th position is: 1

basic_string::find_last_not_ofbasic_string::find_last_not_of

Recherche dans une chaîne le dernier caractère qui n’est pas un élément d’une chaîne spécifiée.Searches through a string for the last character that isn't any element of a specified string.

size_type find_last_not_of(
    value_type char_value,
    size_type offset = npos) const;

size_type find_last_not_of(
    const value_type* ptr,
    size_type offset = npos) const;

size_type find_last_not_of(
    const value_type* ptr,
    size_type offset,
    size_type count) const;

size_type find_last_not_of(
    const basic_string<CharType, Traits, Allocator>& str,
    size_type offset = npos) const;

ParamètresParameters

char_valuechar_value
Valeur de caractère que la fonction membre doit rechercher.The character value for which the member function is to search.

décalageoffset
Index de la position à laquelle la recherche doit se terminer.Index of the position at which the search is to finish.

\ ptrptr</span> C-string que la fonction membre doit rechercher.The C-string for which the member function is to search.

nombre count
Nombre de caractères, en comptant à partir du premier caractère, dans le C-string que la fonction membre doit rechercher.The number of characters, counting forward from the first character, in the C-string for which the member function is to search.

str str
Chaîne que la fonction membre doit rechercher.The string for which the member function is to search.

Valeur de retourReturn Value

Index du premier caractère de la sous-chaîne recherchée en cas de succès ; dans le cas contraire, npos.The index of the first character of the substring searched for when successful; otherwise npos.

ExempleExample

// basic_string_find_last_not_of.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;

   // The first member function
   // searches for a single character in a string
   string str1 ( "dddd-1dd4-abdd" );
   cout << "The original string str1 is: " << str1 << endl;
   basic_string <char>::size_type indexCh1a, indexCh1b;
   static const basic_string <char>::size_type npos = -1;

   indexCh1a = str1.find_last_not_of ( "d" , 7 );
   if ( indexCh1a != npos )
      cout << "The index of the last non 'd'\n found before the "
           << "7th position in str1 is: " << indexCh1a << endl;
   else
      cout << "The non 'd' character was not found ." << endl;

   indexCh1b = str1.find_last_not_of  ( "d" );
   if ( indexCh1b != npos )
      cout << "The index of the non 'd' found in str1 is: "
           << indexCh1b << endl << endl;
   else
      cout << "The Character 'non x' was not found in str1."
           << endl << endl;

   // The second member function searches a string
   // for a substring as specified by a C-string
   string str2 ( "BBB-1111" );
   cout << "The original string str2 is: " << str2 << endl;
   basic_string <char>::size_type indexCh2a, indexCh2b;

   const char *cstr2 = "B1";
   indexCh2a = str2.find_last_not_of  ( cstr2 , 6 );
   if ( indexCh2a != npos )
      cout << "The index of the last occurrence of a "
           << "element\n not of 'B1' in str2 before the 6th "
           << "position is: " << indexCh2a << endl;
   else
      cout << "Elements not of the substring 'B1' were not "
           << "\n found in str2 before the 6th position."
           << endl;

   const char *cstr2b = "B-1";
   indexCh2b = str2.find_last_not_of  ( cstr2b );
   if ( indexCh2b != npos )
      cout << "The index of the last element not "
           << "in 'B-1'\n is: "
           << indexCh2b << endl << endl;
   else
      cout << "The elements of the substring 'B-1' were "
           << "not found in str2 ."
           << endl << endl;

   // The third member function searches a string
   // for a substring as specified by a C-string
   string str3 ( "444-555-GGG" );
   cout << "The original string str3 is: " << str3 << endl;
   basic_string <char>::size_type indexCh3a, indexCh3b;

   const char *cstr3a = "45G";
   indexCh3a = str3.find_last_not_of ( cstr3a );
   if ( indexCh3a != npos )
      cout << "The index of the last occurrence of an "
           << "element in str3\n other than one of the "
           << "characters in '45G' is: " << indexCh3a
           << endl;
   else
      cout << "Elements in str3 contain only characters "
           << " in the string  '45G'. "
           << endl;

   const char *cstr3b = "45G";
   indexCh3b = str3.find_last_not_of ( cstr3b , 6 , indexCh3a - 1 );
   if (indexCh3b != npos )
      cout << "The index of the penultimate occurrence of an "
           << "element\n not in '45G' in str3 is: "
           << indexCh3b << endl << endl;
   else
      cout << "Elements in str3 contain only characters "
           << " in the string '45G'. "
           << endl  << endl;

   // The fourth member function searches a string
   // for a substring as specified by a string
   string str4 ( "12-ab-12-ab" );
   cout << "The original string str4 is: " << str4 << endl;
   basic_string <char>::size_type indexCh4a, indexCh4b;

   string str4a ( "b-a" );
   indexCh4a = str4.find_last_not_of  ( str4a , 5 );
   if ( indexCh4a != npos )
      cout << "The index of the last occurrence of an "
           << "element not\n in 'b-a' in str4 before the 5th "
           << "position is: " << indexCh4a << endl;
   else
      cout << "Elements other than those in the substring"
           << " 'b-a' were not found in the string str4."
           << endl;

   string str4b ( "12" );
   indexCh4b = str4.find_last_not_of ( str4b  );
   if ( indexCh4b != npos )
      cout << "The index of the last occurrence of an "
           << "element not in '12'\n in str4 before the end "
           << "position is: " << indexCh4b << endl;
   else
      cout << "Elements other than those in the substring"
           << " '12'\n were not found in the string str4."
           << endl;
}
The original string str1 is: dddd-1dd4-abdd
The index of the last non 'd'
found before the 7th position in str1 is: 5
The index of the non 'd' found in str1 is: 11

The original string str2 is: BBB-1111
The index of the last occurrence of a element
not of 'B1' in str2 before the 6th position is: 3
The elements of the substring 'B-1' were not found in str2 .

The original string str3 is: 444-555-GGG
The index of the last occurrence of an element in str3
other than one of the characters in '45G' is: 7
The index of the penultimate occurrence of an element
not in '45G' in str3 is: 3

The original string str4 is: 12-ab-12-ab
The index of the last occurrence of an element not
in 'b-a' in str4 before the 5th position is: 1
The index of the last occurrence of an element not in '12'
in str4 before the end position is: 10

basic_string::find_last_ofbasic_string::find_last_of

Recherche dans une chaîne le dernier caractère qui correspond à un élément de la chaîne spécifiée.Searches through a string for the last character that matches any element of a specified string.

size_type find_last_of(
    value_type char_value,
    size_type offset = npos) const;

size_type find_last_of(
    const value_type* ptr,
    size_type offset = npos) const;

size_type find_last_of(
    const value_type* ptr,
    size_type offset,
    size_type count) const;

size_type find_last_of(
    const basic_string<CharType, Traits, Allocator>& str,
    size_type offset = npos) const;

ParamètresParameters

char_valuechar_value
Valeur de caractère que la fonction membre doit rechercher.The character value for which the member function is to search.

décalageoffset
Index de la position à laquelle la recherche doit se terminer.Index of the position at which the search is to finish.

\ ptrptr</span> C-string que la fonction membre doit rechercher.The C-string for which the member function is to search.

nombre count
Nombre de caractères, en comptant à partir du premier caractère, dans le C-string que la fonction membre doit rechercher.The number of characters, counting forward from the first character, in the C-string for which the member function is to search.

str str
Chaîne que la fonction membre doit rechercher.The string for which the member function is to search.

Valeur de retourReturn Value

Index du dernier caractère de la sous-chaîne recherchée en cas de réussite ; sinon, npos.The index of the last character of the substring searched for when successful; otherwise npos.

ExempleExample

// basic_string_find_last_of.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;

   // The first member function
   // searches for a single character in a string
   string str1 ( "abcd-1234-abcd-1234" );
   cout << "The original string str1 is: " << str1 << endl;
   basic_string <char>::size_type indexCh1a, indexCh1b;
   static const basic_string <char>::size_type npos = -1;

   indexCh1a = str1.find_last_of ( "d" , 14 );
   if ( indexCh1a != npos )
      cout << "The index of the last 'd' found before the 14th"
           << " position in str1 is: " << indexCh1a << endl;
   else
      cout << "The character 'd' was not found in str1 ." << endl;

   indexCh1b = str1.find_first_of ( "x" );
   if ( indexCh1b != npos )
      cout << "The index of the 'x' found in str1 is: "
           << indexCh1b << endl << endl;
   else
      cout << "The character 'x' was not found in str1."
           << endl << endl;

   // The second member function searches a string
   // for a substring as specified by a C-string
   string str2 ( "ABCD-1234-ABCD-1234" );
   cout << "The original string str2 is: " << str2 << endl;
   basic_string <char>::size_type indexCh2a, indexCh2b;

   const char *cstr2 = "B1";
   indexCh2a = str2.find_last_of  ( cstr2 , 12 );
   if (indexCh2a != npos )
      cout << "The index of the last occurrence of an "
           << "element of 'B1' in str2 before\n the 12th "
           << "position is: " << indexCh2a << endl;
   else
      cout << "Elements of the substring 'B1' were not "
           << "found in str2 before the 12th position."
           << endl;

   const char *cstr2b = "D2";
   indexCh2b = str2.find_last_of  ( cstr2b );
   if ( indexCh2b != npos )
      cout << "The index of the last element of 'D2' "
           << "after\n the 0th position in str2 is: "
           << indexCh2b << endl << endl;
   else
      cout << "The substring 'D2' was not found in str2 ."
           << endl << endl << endl;

   // The third member function searches a string
   // for a substring as specified by a C-string
   string str3 ( "456-EFG-456-EFG" );
   cout << "The original string str3 is: " << str3 << endl;
   basic_string <char>::size_type indexCh3a;

   const char *cstr3a = "5E";
   indexCh3a = str3.find_last_of ( cstr3a , 8 , 8 );
   if ( indexCh3a != npos )
      cout << "The index of the last occurrence of an "
           << "element of '5E' in str3 before\n the 8th "
           << "position is: " << indexCh3a << endl << endl;
   else
      cout << "Elements of the substring '5G' were not "
           << "found in str3\n before the 8th position."
           << endl << endl;

   // The fourth member function searches a string
   // for a substring as specified by a string
   string str4 ( "12-ab-12-ab" );
   cout << "The original string str4 is: " << str4 << endl;
   basic_string <char>::size_type indexCh4a, indexCh4b;

   string str4a ( "ba3" );
   indexCh4a = str4.find_last_of  ( str4a , 8 );
   if ( indexCh4a != npos )
      cout << "The index of the last occurrence of an "
           << "element of 'ba3' in str4 before\n the 8th "
           << "position is: " << indexCh4a << endl;
   else
      cout << "Elements of the substring 'ba3' were not "
           << "found in str4\n after the 0th position."
           << endl;

   string str4b ( "a2" );
   indexCh4b = str4.find_last_of ( str4b  );
   if ( indexCh4b != npos )
      cout << "The index of the last occurrence of an "
           << "element of 'a2' in str4 before\n the 0th "
           << "position is: " << indexCh4b << endl;
   else
      cout << "Elements of the substring 'a2' were not "
           << "found in str4\n after the 0th position."
           << endl;
}
The original string str1 is: abcd-1234-abcd-1234
The index of the last 'd' found before the 14th position in str1 is: 13
The character 'x' was not found in str1.

The original string str2 is: ABCD-1234-ABCD-1234
The index of the last occurrence of an element of 'B1' in str2 before
the 12th position is: 11
The index of the last element of 'D2' after
the 0th position in str2 is: 16

The original string str3 is: 456-EFG-456-EFG
The index of the last occurrence of an element of '5E' in str3 before
the 8th position is: 4

The original string str4 is: 12-ab-12-ab
The index of the last occurrence of an element of 'ba3' in str4 before
the 8th position is: 4
The index of the last occurrence of an element of 'a2' in str4 before
the 0th position is: 9

basic_string::frontbasic_string::front

Retourne une référence au premier élément d'une chaîne.Returns a reference to the first element in a string.

const_reference front() const;

reference front();

Valeur de retourReturn Value

Référence au premier élément de la chaîne, qui doit être non vide.A reference to the first element of the string, which must be non-empty.

NotesRemarks

basic_string::get_allocatorbasic_string::get_allocator

Retourne une copie de l’objet allocateur utilisé pour construire la chaîne.Returns a copy of the allocator object used to construct the string.

allocator_type get_allocator() const;

Valeur de retourReturn Value

Allocateur utilisé par la chaîne.The allocator used by the string.

NotesRemarks

La fonction membre retourne l’objet d’allocateur stocké.The member function returns the stored allocator object.

Les allocateurs de la classe string spécifient la façon dont la classe gère le stockage.Allocators for the string class specify how the class manages storage. Les allocateurs par défaut fournis avec les classes de conteneur sont suffisants pour la plupart des besoins en programmation.The default allocators supplied with container classes are sufficient for most programming needs. L'écriture et l'utilisation de votre propre classe d'allocateur font l'objet d'une rubrique avancée du langage C++.Writing and using your own allocator class is an advanced C++ topic.

ExempleExample

// basic_string_get_allocator.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;
   // The following lines declare objects
   // that use the default allocator.
   string s1;
   basic_string <char> s2;
   basic_string <char, char_traits< char >, allocator< char > > s3;

   // s4 will use the same allocator class as s1
   basic_string <char> s4( s1.get_allocator ( ) );

   basic_string <char>::allocator_type xchar = s1.get_allocator( );
   // You can now call functions on the allocator class xchar used by s1
}

basic_string::insertbasic_string::insert

Insère un élément, un certain nombre d'éléments ou une plage d'éléments dans la chaîne à la position spécifiée.Inserts an element or a number of elements or a range of elements into the string at a specified position.

basic_string<CharType, Traits, Allocator>& insert(
    size_type position,
    const value_type* ptr);

basic_string<CharType, Traits, Allocator>& insert(
    size_type position,
    const value_type* ptr,
    size_type count);

basic_string<CharType, Traits, Allocator>& insert(
    size_type position,
    const basic_string<CharType, Traits, Allocator>& str);

basic_string<CharType, Traits, Allocator>& insert(
    size_type position,
    const basic_string<CharType, Traits, Allocator>& str,
    size_type offset,
    size_type count);

basic_string<CharType, Traits, Allocator>& insert(
    size_type position,
    size_type count,
    value_type char_value);

iterator insert(
    iterator iter);

iterator insert(
    iterator iter,
    value_type char_value)l
template <class InputIterator>
void insert(
    iterator iter,
    InputIterator first,
    InputIterator last);

void insert(
    iterator iter,
    size_type count,
    value_type char_value);

void insert(
    iterator iter,
    const_pointer first,
    const_pointer last);

void insert(
    iterator iter,
    const_iterator first,
    const_iterator last);

ParamètresParameters

positionposition
Index de la position derrière le point d’insertion des nouveaux caractères.The index of the position behind the point of insertion the new characters.

\ ptrptr</span> C-string à insérer en intégralité ou en partie dans la chaîne.The C-string to be wholly or partly inserted into the string.

nombre count
Nombre de caractères à insérer.The number of characters to be inserted.

str str
Chaîne à insérer en intégralité ou en partie dans la chaîne cible.The string to be wholly or partly inserted into the target string.

décalageoffset
Index de la partie de la chaîne source fournissant les caractères à ajouter.The index of the part of the source string supplying the characters to be appended.

char_valuechar_value
Valeur de caractère des éléments à insérer.The character value of the elements to be inserted.

iteriter
Itérateur traitant la position derrière laquelle un caractère doit être inséré.An iterator addressing the position behind which a character is to be inserted.

premier first
Itérateur d'entrée, const_pointer ou const_iterator qui traite le premier élément dans la plage source à insérer.An input iterator, const_pointer, or const_iterator addressing the first element in the source range to be inserted.

dernier last
Itérateur d'entrée, const_pointer ou const_iterator qui traite la position de l'objet au-delà du dernier élément dans la plage source à insérer.An input iterator, const_pointer, or const_iterator addressing the position of the one beyond the last element in the source range to be inserted.

Valeur de retourReturn Value

Référence à l’objet string auquel la fonction membre affecte de nouveaux caractères ou, dans le cas d’insertions de caractères individuels, itérateur traitant la position du caractère inséré, ou aucune valeur, selon la fonction membre en question.Either a reference to the string object that is being assigned new characters by the member function or, in the case of individual character insertions, an iterator addressing the position of the character inserted, or none, depending on the particular member function.

ExempleExample

// basic_string_insert.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;

   // The first member function inserting a C-string
   // at a given position
   basic_string <char> str1a ( "way" );
   const char *cstr1a = "a";
   str1a.insert ( 0, cstr1a );
   cout << "The string with a C-string inserted at position 0 is: "
        << str1a << "." << endl;

   // The second member function inserting a C-string
   // at a given position for a specified number of elements
   basic_string <char> str2a ( "Good" );
   const char *cstr2a = "Bye Bye Baby";
   str2a.insert ( 4, cstr2a ,3 );
   cout << "The string with a C-string inserted at the end is: "
        << str2a << "." << endl;

   // The third member function inserting a string
   // at a given position
   basic_string <char> str3a ( "Bye" );
   string str3b ( "Good" );
   str3a.insert ( 0, str3b );
   cout << "The string with a string inserted at position 0 is: "
        << str3a << "." << endl;

   // The fourth member function inserting part of
   // a string at a given position
   basic_string <char> str4a ( "Good " );
   string str4b ( "Bye Bye Baby" );
   str4a.insert ( 5, str4b , 8 , 4 );
   cout << "The string with part of a string inserted at position 4 is: "
        << str4a << "." << endl;

   // The fifth member function inserts a number of characters
   // at a specified position in the string
   string str5 ( "The number is: ." );
   str5.insert ( 15 , 3 , '3' );
   cout << "The string with characters inserted is: "
        << str5 << endl;

   // The sixth member function inserts a character
   // at a specified position in the string
   string str6 ( "ABCDFG" );
   basic_string <char>::iterator str6_Iter = ( str6.begin ( ) + 4 );
   str6.insert ( str6_Iter , 'e' );
   cout << "The string with a character inserted is: "
        << str6 << endl;

   // The seventh member function inserts a range
   // at a specified position in the string
   string str7a ( "ABCDHIJ" );
   string str7b ( "abcdefgh" );
   basic_string <char>::iterator str7a_Iter = (str7a.begin ( ) + 4 );
   str7a.insert ( str7a_Iter , str7b.begin ( ) + 4 , str7b.end ( ) -1 );
   cout << "The string with a character inserted from a range is: "
        << str7a << endl;

   // The eigth member function inserts a number of
   // characters at a specified position in the string
   string str8 ( "ABCDHIJ" );
   basic_string <char>::iterator str8_Iter = ( str8.begin ( ) + 4 );
   str8.insert ( str8_Iter , 3 , 'e' );
   cout << "The string with a character inserted from a range is: "
        << str8 << endl;
}
The string with a C-string inserted at position 0 is: away.
The string with a C-string inserted at the end is: GoodBye.
The string with a string inserted at position 0 is: GoodBye.
The string with part of a string inserted at position 4 is: Good Baby.
The string with characters inserted is: The number is: 333.
The string with a character inserted is: ABCDeFG
The string with a character inserted from a range is: ABCDefgHIJ
The string with a character inserted from a range is: ABCDeeeHIJ

basic_string::iteratorbasic_string::iterator

Type qui fournit un itérateur d’accès aléatoire pouvant accéder à un élément const et le lire dans la chaîne.A type that provides a random-access iterator that can access and read a const element in the string.

typedef implementation-defined iterator;

NotesRemarks

Un iterator de type peut être utilisé pour modifier la valeur d’un caractère et est utilisé pour itérer au sein d’une chaîne vers l’avant.A type iterator can be used to modify the value of a character and is used to iterate through a string in a forward direction.

ExempleExample

Pour savoir comment déclarer et utiliser iterator, consultez l’exemple relatif à begin.See the example for begin for an example of how to declare and use iterator.

basic_string::lengthbasic_string::length

Retourne le nombre actuel d'éléments contenus dans une chaîne.Returns the current number of elements in a string.

size_type length() const;

NotesRemarks

La fonction membre est identique à size.The member function is the same as size.

ExempleExample

// basic_string_length.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;
   string str1 ("Hello world");
   cout << "The original string str1 is: " << str1 << endl;

   // The size and length member functions differ in name only
   basic_string <char>::size_type sizeStr1, lenStr1;
   sizeStr1 = str1.size ( );
   lenStr1 = str1.length ( );

   basic_string <char>::size_type capStr1, max_sizeStr1;
   capStr1 = str1.capacity ( );
   max_sizeStr1 = str1.max_size ( );

   // Compare size, length, capacity & max_size of a string
   cout << "The current size of original string str1 is: "
        << sizeStr1 << "." << endl;
   cout << "The current length of original string str1 is: "
        << lenStr1 << "." << endl;
   cout << "The capacity of original string str1 is: "
        << capStr1 << "." << endl;
   cout << "The max_size of original string str1 is: "
        << max_sizeStr1 << "." << endl << endl;

   str1.erase ( 6, 5 );
   cout << "The modified string str1 is: " << str1 << endl;

   sizeStr1 = str1.size ( );
   lenStr1 = str1.length ( );
   capStr1 = str1.capacity ( );
   max_sizeStr1 = str1.max_size ( );

   // Compare size, length, capacity & max_size of a string
   // after erasing part of the original string
   cout << "The current size of modified string str1 is: "
        << sizeStr1 << "." << endl;
   cout << "The current length of modified string str1 is: "
        << lenStr1 << "." << endl;
   cout << "The capacity of modified string str1 is: "
        << capStr1 << "." << endl;
   cout << "The max_size of modified string str1 is: "
        << max_sizeStr1 << "." << endl;
}

basic_string::max_sizebasic_string::max_size

Retourne le nombre maximal de caractères qu'une chaîne peut contenir.Returns the maximum number of characters a string could contain.

size_type max_size() const;

Valeur de retourReturn Value

Nombre maximal de caractères qu’une chaîne peut contenir.The maximum number of characters a string could contain.

NotesRemarks

Une exception de type classe length_error est levée quand une opération produit une chaîne d’une longueur supérieure à la taille maximale.A exception of type length_error Class is thrown when an operation produces a string with a length greater than the maximum size.

ExempleExample

// basic_string_max_size.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;
   string str1 ("Hello world");
   cout << "The original string str1 is: " << str1 << endl;

   // The size and length member functions differ in name only
   basic_string <char>::size_type sizeStr1, lenStr1;
   sizeStr1 = str1.size ( );
   lenStr1 = str1.length ( );

   basic_string <char>::size_type capStr1, max_sizeStr1;
   capStr1 = str1.capacity ( );
   max_sizeStr1 = str1.max_size ( );

   // Compare size, length, capacity & max_size of a string
   cout << "The current size of original string str1 is: "
        << sizeStr1 << "." << endl;
   cout << "The current length of original string str1 is: "
        << lenStr1 << "." << endl;
   cout << "The capacity of original string str1 is: "
        << capStr1 << "." << endl;
   cout << "The max_size of original string str1 is: "
        << max_sizeStr1 << "." << endl << endl;

   str1.erase ( 6, 5 );
   cout << "The modified string str1 is: " << str1 << endl;

   sizeStr1 = str1.size ( );
   lenStr1 = str1.length ( );
   capStr1 = str1.capacity ( );
   max_sizeStr1 = str1.max_size ( );

   // Compare size, length, capacity & max_size of a string
   // after erasing part of the original string
   cout << "The current size of modified string str1 is: "
        << sizeStr1 << "." << endl;
   cout << "The current length of modified string str1 is: "
        << lenStr1 << "." << endl;
   cout << "The capacity of modified string str1 is: "
        << capStr1 << "." << endl;
   cout << "The max_size of modified string str1 is: "
        << max_sizeStr1 << "." << endl;
}

basic_string::nposbasic_string::npos

Valeur intégrale non signée initialisée à-1 qui indique « introuvable » ou « tous les caractères restants » quand une fonction de recherche échoue.An unsigned integral value initialized to -1 that indicates either "not found" or "all remaining characters" when a search function fails.

static const size_type npos = -1;

NotesRemarks

Lorsque la valeur de retour doit être vérifiée pour la valeur npos, elle peut ne pas fonctionner, sauf si la valeur de retour est de type size_type et non int ou unsigned.When the return value is to be checked for the npos value, it might not work unless the return value is of type size_type and not either int or unsigned.

ExempleExample

Consultez l’exemple relatif à find pour savoir comment déclarer et utiliser npos.See the example for find for an example of how to declare and use npos.

basic_string::operator+=basic_string::operator+=

Ajoute des caractères à une chaîne.Appends characters to a string.

basic_string<CharType, Traits, Allocator>& operator+=(
    value_type char_value);

basic_string<CharType, Traits, Allocator>& operator+=(
    const value_type* ptr);

basic_string<CharType, Traits, Allocator>& operator+=(
    const basic_string<CharType, Traits, Allocator>& right);

ParamètresParameters

char_valuechar_value
Caractère à ajouter.The character to be appended.

\ ptrptr</span> Caractères de la chaîne C à ajouter.The characters of the C-string to be appended.

\ droitright</span> Caractères de la chaîne à ajouter.The characters of the string to be appended.

Valeur de retourReturn Value

Référence à l’objet string ajouté avec les caractères transmis par la fonction membre.A reference to the string object that is being appended with the characters passed by the member function.

NotesRemarks

Les caractères peuvent être ajoutés à une chaîne à l’aide de operator+=, ou des fonctions membres append ou push_back.Characters may be appended to a string using the operator+= or the member functions append or push_back. operator+= ajoute des valeurs à argument unique tandis que la fonction membre append à plusieurs arguments permet de spécifier une partie spécifique d’une chaîne à ajouter.The operator+= appends single-argument values while the multiple argument append member function allows a specific part of a string to be specified for adding.

ExempleExample

// basic_string_op_app.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;

   // The first member function
   // appending a single character to a string
   string str1a ( "Hello" );
   cout << "The original string str1 is: " << str1a << endl;
   str1a +=  '!' ;
   cout << "The string str1 appended with an exclamation is: "
        << str1a << endl << endl;

   // The second member function
   // appending a C-string to a string
   string  str1b ( "Hello " );
   const char *cstr1b = "Out There";
   cout << "The C-string cstr1b is: " << cstr1b << endl;
   str1b +=  cstr1b;
   cout << "Appending the C-string cstr1b to string str1 gives: "
        << str1b << "." << endl << endl;

   // The third member function
   // appending one string to another in two ways,
   // comparing append and operator [ ]
   string str1d ( "Hello " ), str2d ( "Wide " ), str3d ( "World" );
   cout << "The string str2d is: " << str2d << endl;
   str1d.append ( str2d );
   cout << "The appended string str1d is: "
        << str1d << "." << endl;
   str1d += str3d;
   cout << "The doubly appended strig str1 is: "
        << str1d << "." << endl << endl;
}
The original string str1 is: Hello
The string str1 appended with an exclamation is: Hello!

The C-string cstr1b is: Out There
Appending the C-string cstr1b to string str1 gives: Hello Out There.

The string str2d is: Wide
The appended string str1d is: Hello Wide .
The doubly appended strig str1 is: Hello Wide World.

basic_string::operator=basic_string::operator=

Assigne de nouvelles valeurs de caractère au contenu d'une chaîne.Assigns new character values to the contents of a string.

basic_string<CharType, Traits, Allocator>& operator=(
    value_type char_value);

basic_string<CharType, Traits, Allocator>& operator=(
    const value_type* ptr);

basic_string<CharType, Traits, Allocator>& operator=(
    const basic_string<CharType, Traits, Allocator>& right);

basic_string<CharType, Traits, Allocator>& operator=(
    const basic_string<CharType, Traits, Allocator>&& right);

ParamètresParameters

char_valuechar_value
Valeur du caractère à assigner.The character value to be assigned.

\ ptrptr</span> Pointeur vers les caractères de la chaîne C à assigner à la chaîne cible.A pointer to the characters of the C-string to be assigned to the target string.

\ droitright</span> Chaîne source dont les caractères doivent être assignés à la chaîne cible.The source string whose characters are to be assigned to the target string.

Valeur de retourReturn Value

Référence à l’objet string auquel la fonction membre assigne les nouveaux caractères.A reference to the string object that is being assigned new characters by the member function.

NotesRemarks

Les chaînes peuvent recevoir de nouvelles valeurs de caractère.The strings may be assigned new character values. La nouvelle valeur peut être une chaîne et une chaîne C, ou un caractère unique.The new value may be either a string and C-string or a single character. operator= peut être utilisé si la nouvelle valeur peut être décrite par un seul paramètre ; sinon la fonction membre assign, qui possède plusieurs paramètres, peut être utilisée pour spécifier la partie de la chaîne qui doit être assignée à une chaîne cible.The operator= may be used if the new value can be described by a single parameter, otherwise the member function assign, which has multiple parameters, may be used to specify which part of the string is to be assigned to a target string.

ExempleExample

// basic_string_op_assign.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;

   // The first member function assigning a
   // character of a certain value to a string
   string str1a ( "Hello " );
   str1a = '0';
   cout << "The string str1 assigned with the zero character is: "
        << str1a << endl << endl;

   // The second member function assigning the
   // characters of a C-string to a string
   string  str1b;
   const char *cstr1b = "Out There";
   cout << "The C-string cstr1b is: " << cstr1b <<  "." << endl;
   str1b = cstr1b;
   cout << "Assigning the C-string cstr1a to string str1 gives: "
        << str1b << "." << endl << endl;

   // The third member function assigning the characters
   // from one string to another string in two equivalent
   // ways, comparing the assign and operator =
   string str1c ( "Hello" ), str2c ( "Wide" ), str3c ( "World" );
   cout << "The original string str1 is: " << str1c << "." << endl;
   cout << "The string str2c is: " << str2c << "." << endl;
   str1c.assign ( str2c );
   cout << "The string str1 newly assigned with string str2c is: "
        << str1c << "." << endl;
   cout << "The string str3c is: " << str3c << "." << endl;
   str1c = str3c;
   cout << "The string str1 reassigned with string str3c is: "
        << str1c << "." << endl << endl;
}
The string str1 assigned with the zero character is: 0

The C-string cstr1b is: Out There.
Assigning the C-string cstr1a to string str1 gives: Out There.

The original string str1 is: Hello.
The string str2c is: Wide.
The string str1 newly assigned with string str2c is: Wide.
The string str3c is: World.
The string str1 reassigned with string str3c is: World.

basic_string::operator[]basic_string::operator[]

Fournit une référence au caractère situé à l'index spécifié dans une chaîne.Provides a reference to the character with a specified index in a string.

const_reference operator[](size_type offset) const;
reference operator[](size_type offset);

ParamètresParameters

décalageoffset
Index de la position de l’élément à référencer.The index of the position of the element to be referenced.

Valeur de retourReturn Value

Référence au caractère de la chaîne à la position spécifiée par l’index de paramètre.A reference to the character of the string at the position specified by the parameter index.

NotesRemarks

Le premier élément de la chaîne a un index égal à zéro et les éléments suivants sont indexés consécutivement par les entiers positifs, de sorte qu’une chaîne de longueur n a son n-ième élément indexé par le nombre n - 1.The first element of the string has an index of zero, and the following elements are indexed consecutively by the positive integers, so that a string of length n has an nth element indexed by the number n - 1.

operator[] est plus rapide que la fonction membre at pour fournir un accès en lecture et en écriture aux éléments d’une chaîne.operator[] is faster than the member function at for providing read and write access to the elements of a string.

operator[] ne vérifie pas si l’index passé comme paramètre est valide, mais la fonction membre at ne doit pas être utilisée dans la validité.operator[] does not check whether the index passed as a parameter is valid, but the member function at does and so should be used in the validity isn't certain. Un index non valide (un index inférieur à zéro ou supérieur ou égal à la taille de la chaîne) passé à la fonction membre at lève une exception de classe out_of_range .An invalid index (an index less that zero or greater than or equal to the size of the string) passed to the member function at throws an out_of_range Class exception. Un index non valide passé à operator[] entraîne un comportement indéfini, mais l’index égal à la longueur de la chaîne est un index valide pour les chaînes const, et l’opérateur retourne le caractère null quand il reçoit cet index.An invalid index passed to operator[] results in undefined behavior, but the index equal to the length of the string is a valid index for const strings and the operator returns the null character when passed this index.

La référence retournée peut être invalidée par des réallocations ou des modifications de chaîne pour les chaînes non-const.The reference returned may be invalidated by string reallocations or modifications for the non- const strings.

Lors d’une compilation avec _ITERATOR_DEBUG_LEVEL défini sur 1 ou 2, une erreur d’exécution se produit si vous tentez d’accéder à un élément en dehors des limites de la chaîne.When compiling with _ITERATOR_DEBUG_LEVEL set to 1 or 2, a runtime error will occur if you attempt to access an element outside the bounds of the string. Pour plus d'informations, consultez Checked Iterators.For more information, see Checked Iterators.

ExempleExample

// basic_string_op_ref.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;
   string str1 ( "Hello world" ), str2 ( "Goodbye world" );
   const string cstr1 ( "Hello there" ), cstr2 ( "Goodbye now" );
   cout << "The original string str1 is: " << str1 << endl;
   cout << "The original string str2 is: " << str2 << endl;

   // Element access to the non-const strings
   basic_string <char>::reference refStr1 = str1 [6];
   basic_string <char>::reference refStr2 = str2.at ( 3 );

   cout << "The character with an index of 6 in string str1 is: "
        << refStr1 << "." << endl;
   cout << "The character with an index of 3 in string str2 is: "
        << refStr2 << "." << endl;

   // Element access to the const strings
   basic_string <char>::const_reference crefStr1 = cstr1 [ cstr1.length ( ) ];
   basic_string <char>::const_reference crefStr2 = cstr2.at ( 8 );

   if ( crefStr1 == '\0' )
      cout << "The null character is returned as a valid reference."
           << endl;
   else
      cout << "The null character is not returned." << endl;
   cout << "The character with index of 8 in the const string cstr2 is: "
        << crefStr2 << "." << endl;
}

basic_string::pointerbasic_string::pointer

Type qui fournit un pointeur vers un élément caractère d'une chaîne ou d'un tableau de caractères.A type that provides a pointer to a character element in a string or character array.

typedef typename allocator_type::pointer pointer;

NotesRemarks

Le type est un synonyme de allocator_type::pointer.The type is a synonym for allocator_type::pointer.

Pour le type string, son équivalent est *char.For type string, it's equivalent to char*.

ExempleExample

// basic_string_pointer.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;
   basic_string<char>::pointer pstr1a = "In Here";
   char *cstr1b = "Out There";
   cout << "The string pstr1a is: " << pstr1a <<  "." << endl;
   cout << "The C-string cstr1b is: " << cstr1b << "." << endl;
}
The string pstr1a is: In Here.
The C-string cstr1b is: Out There.

basic_string::pop_backbasic_string::pop_back

Efface le dernier élément de la chaîne.Erases the last element of the string.

void pop_back();

NotesRemarks

Cette fonction membre appelle erase(size() - 1) pour effacer le dernier élément de la séquence, qui ne doit pas être vide.This member function effectively calls erase(size() - 1) to erase the last element of the sequence, which must be non-empty.

basic_string::push_backbasic_string::push_back

Ajoute un élément à la fin de la chaîne.Adds an element to the end of the string.

void push_back(value_type char_value);

ParamètresParameters

char_valuechar_value
Caractère à ajouter à la fin de la chaîne.The character to be added to the end of the string.

NotesRemarks

La fonction membre appelle effectivement Insert( end, char_value ).The member function effectively calls insert( end, char_value ).

ExempleExample

// basic_string_push_back.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;
   string str1 ( "abc" );
   basic_string <char>::iterator str_Iter, str1_Iter;

   cout << "The original string str1 is: ";
   for ( str_Iter = str1.begin( ); str_Iter != str1.end( ); str_Iter++ )
      cout << *str_Iter;
   cout << endl;

   // str1.push_back ( 'd' );
   str1_Iter = str1.end ( );
   str1_Iter--;
   cout << "The last character-letter of the modified str1 is now: "
        << *str1_Iter << endl;

   cout << "The modified string str1 is: ";
   for ( str_Iter = str1.begin( ); str_Iter != str1.end( ); str_Iter++ )
      cout << *str_Iter;
   cout << endl;
}
The original string str1 is: abc
The last character-letter of the modified str1 is now: c
The modified string str1 is: abc

basic_string::rbeginbasic_string::rbegin

Retourne un itérateur au premier élément d'une chaîne inversée.Returns an iterator to the first element in a reversed string.

const_reverse_iterator rbegin() const;

reverse_iterator rbegin();

Valeur de retourReturn Value

Retourne un itérateur d’accès aléatoire vers le premier élément d’une chaîne inversée, qui cible le dernier élément de la chaîne non inversée correspondante.Returns a random-access iterator to the first element in a reversed string, addressing what would be the last element in the corresponding unreversed string.

NotesRemarks

rbegin est utilisé avec une chaîne inversée, de la même façon que begin est utilisé avec une chaîne.rbegin is used with a reversed string just as begin is used with a string.

Si la valeur de retour de rbegin est assignée à un const_reverse_iterator, l’objet de chaîne ne peut pas être modifié.If the return value of rbegin is assigned to a const_reverse_iterator, the string object cannot be modified. Si la valeur de retour de rbegin est assignée à un reverse_iterator, l’objet de chaîne peut être modifié.If the return value of rbegin is assigned to a reverse_iterator, the string object can be modified.

rbegin peut être utilisé pour initialiser une itération au sein d’une chaîne vers l’arrière.rbegin can be used to initialize an iteration through a string backwards.

ExempleExample

// basic_string_rbegin.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;
   string str1 ( "Able was I ere I saw Elba" ), str2;
   basic_string <char>::reverse_iterator str_rIter, str1_rIter, str2_rIter;
   basic_string <char>::const_reverse_iterator str1_rcIter;

   str1_rIter = str1.rbegin ( );
   // str1_rIter--;
   cout << "The first character-letter of the reversed string str1 is: "
        << *str1_rIter << endl;
   cout << "The full reversed string str1 is:\n ";
   for ( str_rIter = str1.rbegin( ); str_rIter != str1.rend( ); str_rIter++ )
      cout << *str_rIter;
   cout << endl;

   // The dereferenced iterator can be used to modify a character
*str1_rIter = 'A';
   cout << "The first character-letter of the modified str1 is now: "
        << *str1_rIter << endl;
   cout << "The full modified reversed string str1 is now:\n ";
   for ( str_rIter = str1.rbegin( ); str_rIter != str1.rend( ); str_rIter++ )
      cout << *str_rIter;
   cout << endl;

   // The following line would be an error because iterator is const
   // *str1_rcIter = 'A';

   // For an empty string, begin is equivalent to end
   if ( str2.rbegin( ) == str2.rend ( ) )
      cout << "The string str2 is empty." << endl;
   else
      cout << "The stringstr2  is not empty." << endl;
}
The first character-letter of the reversed string str1 is: a
The full reversed string str1 is:
ablE was I ere I saw elbA
The first character-letter of the modified str1 is now: A
The full modified reversed string str1 is now:
AblE was I ere I saw elbA
The string str2 is empty.

basic_string::referencebasic_string::reference

Type qui fournit une référence à un élément stocké dans une chaîne.A type that provides a reference to an element stored in a string.

typedef typename allocator_type::reference reference;

NotesRemarks

Un reference de type peut être utilisé pour modifier la valeur d’un élément.A type reference can be used to modify the value of an element.

Le type est un synonyme de allocator_type::reference.The type is a synonym for allocator_type::reference.

Pour le type string, il est équivalent à chr&.For type string, it's equivalent to chr&.

ExempleExample

Pour savoir comment déclarer et utiliser reference, consultez l’exemple relatif à at.See the example for at for an example of how to declare and use reference.

basic_string::rendbasic_string::rend

Retourne un itérateur qui cible l’emplacement suivant le dernier élément d’une chaîne inversée.Returns an iterator that addresses the location succeeding the last element in a reversed string.

const_reverse_iterator rend() const;

reverse_iterator rend();

Valeur de retourReturn Value

Retourne un itérateur d’accès aléatoire qui cible l’emplacement suivant le dernier élément d’une chaîne inversée.A reverse random-access iterator that addresses the location succeeding the last element in a reversed string.

NotesRemarks

rend est utilisé avec une chaîne inversée, de la même façon que end est utilisé avec une chaîne.rend is used with a reversed string just as end is used with a string.

Si la valeur de retour de rend est assignée à un const_reverse_iterator, l’objet de chaîne ne peut pas être modifié.If the return value of rend is assigned to a const_reverse_iterator, the string object cannot be modified. Si la valeur de retour de rend est assignée à un reverse_iterator, l’objet de chaîne peut être modifié.If the return value of rend is assigned to a reverse_iterator, the string object can be modified.

rend peut être utilisé pour déterminer si un itérateur inversé a atteint la fin de sa chaîne.rend can be used to test whether a reverse iterator has reached the end of its string.

La valeur retournée par rend ne doit pas être déréférencée.The value returned by rend shouldn't be dereferenced.

ExempleExample

// basic_string_rend.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;
   string str1 ("Able was I ere I saw Elba"), str2;
   basic_string <char>::reverse_iterator str_rIter, str1_rIter, str2_rIter;
   basic_string <char>::const_reverse_iterator str1_rcIter;

   str1_rIter = str1.rend ( );
   str1_rIter--;
   cout << "The last character-letter of the reversed string str1 is: "
        << *str1_rIter << endl;
   cout << "The full reversed string str1 is:\n ";
   for ( str_rIter = str1.rbegin( ); str_rIter != str1.rend( ); str_rIter++ )
      cout << *str_rIter;
   cout << endl;

   // The dereferenced iterator can be used to modify a character
*str1_rIter = 'o';
   cout << "The last character-letter of the modified str1 is now: "
        << *str1_rIter << endl;
   cout << "The full modified reversed string str1 is now:\n ";
   for ( str_rIter = str1.rbegin( ); str_rIter != str1.rend( ); str_rIter++ )
      cout << *str_rIter;
   cout << endl;

   // The following line would be an error because iterator is const
   // *str1_rcIter = 'T';

   // For an empty string, end is equivalent to begin
   if ( str2.rbegin( ) == str2.rend ( ) )
      cout << "The string str2 is empty." << endl;
   else
      cout << "The stringstr2  is not empty." << endl;
}
The last character-letter of the reversed string str1 is: A
The full reversed string str1 is:
ablE was I ere I saw elbA
The last character-letter of the modified str1 is now: o
The full modified reversed string str1 is now:
ablE was I ere I saw elbo
The string str2 is empty.

basic_string::replacebasic_string::replace

Remplace les éléments d'une chaîne à la position spécifiée par des caractères spécifiques ou des caractères copiés à partir d'autres plages, chaînes ou chaînes de style C.Replaces elements in a string at a specified position with specified characters or characters copied from other ranges or strings or C-strings.

basic_string<CharType, Traits, Allocator>& replace(
    size_type position_1,
    size_type number_1,
    const value_type* ptr);

basic_string<CharType, Traits, Allocator>& replace(
    size_type position_1,
    size_type number_1,
    const basic_string<CharType, Traits, Allocator>& str);

basic_string<CharType, Traits, Allocator>& replace(
    size_type position_1,
    size_type number_1,
    const value_type* ptr,
    size_type number_2);

basic_string<CharType, Traits, Allocator>& replace(
    size_type position_1,
    size_type number_1,
    const basic_string<CharType, Traits, Allocator>& str,
    size_type position_2,
    size_type number_2);

basic_string<CharType, Traits, Allocator>& replace(
    size_type position_1,
    size_type number_1,
    size_type count,
    value_type char_value);

basic_string<CharType, Traits, Allocator>& replace(
    iterator first0,
    iterator last0,
    const value_type* ptr);

basic_string<CharType, Traits, Allocator>& replace(
    iterator first0,
    iterator last0,
    const basic_string<CharType, Traits, Allocator>& str);

basic_string<CharType, Traits, Allocator>& replace(
    iterator first0,
    iterator last0,
    const value_type* ptr,
    size_type number_2);

basic_string<CharType, Traits, Allocator>& replace(
    iterator first0,
    iterator last0,
    size_type number_2,
    value_type char_value);

template <class InputIterator>
basic_string<CharType, Traits, Allocator>& replace(
    iterator first0,
    iterator last0,
    InputIterator first,
    InputIterator last);

basic_string<CharType, Traits, Allocator>& replace(
    iterator first0,
    iterator last0,
    const_pointer first,
    const_pointer last);

basic_string<CharType, Traits, Allocator>& replace(
    iterator first0,
    iterator last0,
    const_iterator first,
    const_iterator last);

ParamètresParameters

str str
Chaîne qui doit être une source de caractères pour la chaîne d’opérande.The string that is to be a source of characters for the operand string.

position_1position_1
Index de la chaîne d’opérande à partir duquel commence le remplacement.The index of the operand string at which the replacement begins.

number_1number_1
Nombre maximal de caractères à remplacer dans la chaîne d’opérande.The maximum number of characters to be replaced in the operand string.

position_2position_2
Index de la chaîne de paramètre à partir duquel commence la copie.The index of the parameter string at which the copying begins.

number_2number_2
Nombre maximal de caractères à utiliser de la chaîne C de paramètre.The maximum number of characters to be used from the parameter C-string.

\ ptrptr</span> Chaîne C qui doit être une source de caractères pour la chaîne d’opérande.The C-string that is to be a source of characters for the operand string.

char_valuechar_value
Caractère à copier dans la chaîne d’opérande.The character to be copied into the operand string.

first0 first0
Itérateur qui cible le premier caractère à supprimer dans la chaîne d’opérande.An iterator addressing the first character to be removed in the operand string.

last0 last0
Itérateur qui cible le dernier caractère à supprimer dans la chaîne d’opérande.An iterator addressing the last character to be removed in the operand string.

premier first
Itérateur, const_pointer ou const_iterator qui cible le premier caractère à copier dans la chaîne de paramètre.An iterator, const_pointer, or const_iterator addressing the first character to be copied in the parameter string.

dernier last
Itérateur, const_pointer ou const_iterator qui cible le dernier caractère à copier dans la chaîne de paramètre.An iterator, const_pointer, or const_iterator addressing the last character to be copied in the parameter string.

nombre count
Nombre de fois où char_value est copié dans la chaîne d’opérande.The number of times char_value is copied into the operand string.

Valeur de retourReturn Value

Chaîne d’opérande avec le remplacement effectué.The operand string with the replacement made.

ExempleExample

// basic_string_replace.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;

   // The first two member functions replace
   // part of the operand string with
   // characters from a parameter string or C-string
   string result1a, result1b;
   string s1o ( "AAAAAAAA" );
   string s1p ( "BBB" );
   const char* cs1p = "CCC";
   cout << "The operand string s1o is: " << s1o << endl;
   cout << "The parameter string s1p is: " << s1p << endl;
   cout << "The parameter C-string cs1p is: " << cs1p << endl;
   result1a = s1o.replace ( 1 , 3 , s1p );
   cout << "The result of s1o.replace ( 1 , 3 , s1p )\n is "
        << "the string: " << result1a << "." << endl;
   result1b = s1o.replace ( 5 , 3 , cs1p );
   cout << "The result of s1o.replace ( 5 , 3 , cs1p )\n is "
        << "the string: " << result1b << "." << endl;
   cout << endl;

   // The third & fourth member function replace
   // part of the operand string with characters
   // form part of a parameter string or C-string
   string result2a, result2b;
   string s2o ( "AAAAAAAA" );
   string s2p ( "BBB" );
   const char* cs2p = "CCC";
   cout << "The operand string s2o is: " << s2o << endl;
   cout << "The parameter string s1p is: " << s2p << endl;
   cout << "The parameter C-string cs2p is: " << cs2p << endl;
   result2a = s2o.replace ( 1 , 3 , s2p , 1 , 2 );
   cout << "The result of s2o.replace (1, 3, s2p, 1, 2)\n is "
        << "the string: " << result2a << "." << endl;
   result2b = s2o.replace ( 4 , 3 , cs2p , 1 );
   cout << "The result of s2o.replace (4 ,3 ,cs2p)\n is "
        << "the string: " << result2b << "." << endl;
   cout << endl;

   // The fifth member function replaces
   // part of the operand string with characters
   string result3a;
   string s3o ( "AAAAAAAA" );
   char ch3p = 'C';
   cout << "The operand string s3o is: " << s3o << endl;
   cout << "The parameter character c1p is: " << ch3p << endl;
   result3a = s3o.replace ( 1 , 3 , 4 , ch3p );
   cout << "The result of s3o.replace(1, 3, 4, ch3p)\n is "
        << "the string: " << result3a << "." << endl;
   cout << endl;

   // The sixth & seventh member functions replace
   // part of the operand string, delineated with iterators,
   // with a parameter string or C-string
   string s4o ( "AAAAAAAA" );
   string s4p ( "BBB" );
   const char* cs4p = "CCC";
   cout << "The operand string s4o is: " << s4o << endl;
   cout << "The parameter string s4p is: " << s4p << endl;
   cout << "The parameter C-string cs4p is: " << cs4p << endl;
   basic_string<char>::iterator IterF0, IterL0;
   IterF0 = s4o.begin ( );
   IterL0 = s4o.begin ( ) + 3;
   string result4a, result4b;
   result4a = s4o.replace ( IterF0 , IterL0 , s4p );
   cout << "The result of s1o.replace (IterF0, IterL0, s4p)\n is "
        << "the string: " << result4a << "." << endl;
   result4b = s4o.replace ( IterF0 , IterL0 , cs4p );
   cout << "The result of s4o.replace (IterF0, IterL0, cs4p)\n is "
        << "the string: " << result4b << "." << endl;
   cout << endl;

   // The 8th member function replaces
   // part of the operand string delineated with iterators
   // with a number of characters from a parameter C-string
   string s5o ( "AAAAAAAF" );
   const char* cs5p = "CCCBB";
   cout << "The operand string s5o is: " << s5o << endl;
   cout << "The parameter C-string cs5p is: " << cs5p << endl;
   basic_string<char>::iterator IterF1, IterL1;
   IterF1 = s5o.begin ( );
   IterL1 = s5o.begin ( ) + 4;
   string result5a;
   result5a = s5o.replace ( IterF1 , IterL1 , cs5p , 4 );
   cout << "The result of s5o.replace (IterF1, IterL1, cs4p ,4)\n is "
        << "the string: " << result5a << "." << endl;
   cout << endl;

   // The 9th member function replaces
   // part of the operand string delineated with iterators
   // with specified characters
   string s6o ( "AAAAAAAG" );
   char ch6p = 'q';
   cout << "The operand string s6o is: " << s6o << endl;
   cout << "The parameter character ch6p is: " << ch6p << endl;
   basic_string<char>::iterator IterF2, IterL2;
   IterF2 = s6o.begin ( );
   IterL2 = s6o.begin ( ) + 3;
   string result6a;
   result6a = s6o.replace ( IterF2 , IterL2 , 4 , ch6p );
   cout << "The result of s6o.replace (IterF1, IterL1, 4, ch6p)\n is "
        << "the string: " << result6a << "." << endl;
   cout << endl;

   // The 10th member function replaces
   // part of the operand string delineated with iterators
   // with part of a parameter string delineated with iterators
   string s7o ( "OOOOOOO" );
   string s7p ( "PPPP" );
   cout << "The operand string s7o is: " << s7o << endl;
   cout << "The parameter string s7p is: " << s7p << endl;
   basic_string<char>::iterator IterF3, IterL3, IterF4, IterL4;
   IterF3 = s7o.begin ( ) + 1;
   IterL3 = s7o.begin ( ) + 3;
   IterF4 = s7p.begin ( );
   IterL4 = s7p.begin ( ) + 2;
   string result7a;
   result7a = s7o.replace ( IterF3 , IterL3 , IterF4 , IterL4 );
   cout << "The result of s7o.replace (IterF3 ,IterL3 ,IterF4 ,IterL4)\n is "
        << "the string: " << result7a << "." << endl;
   cout << endl;
}
The operand string s1o is: AAAAAAAA
The parameter string s1p is: BBB
The parameter C-string cs1p is: CCC
The result of s1o.replace ( 1 , 3 , s1p )
is the string: ABBBAAAA.
The result of s1o.replace ( 5 , 3 , cs1p )
is the string: ABBBACCC.

The operand string s2o is: AAAAAAAA
The parameter string s1p is: BBB
The parameter C-string cs2p is: CCC
The result of s2o.replace (1, 3, s2p, 1, 2)
is the string: ABBAAAA.
The result of s2o.replace (4 ,3 ,cs2p)
is the string: ABBAC.

The operand string s3o is: AAAAAAAA
The parameter character c1p is: C
The result of s3o.replace(1, 3, 4, ch3p)
is the string: ACCCCAAAA.

The operand string s4o is: AAAAAAAA
The parameter string s4p is: BBB
The parameter C-string cs4p is: CCC
The result of s1o.replace (IterF0, IterL0, s4p)
is the string: BBBAAAAA.
The result of s4o.replace (IterF0, IterL0, cs4p)
is the string: CCCAAAAA.

The operand string s5o is: AAAAAAAF
The parameter C-string cs5p is: CCCBB
The result of s5o.replace (IterF1, IterL1, cs4p ,4)
is the string: CCCBAAAF.

The operand string s6o is: AAAAAAAG
The parameter character ch6p is: q
The result of s6o.replace (IterF1, IterL1, 4, ch6p)
is the string: qqqqAAAAG.

The operand string s7o is: OOOOOOO
The parameter string s7p is: PPPP
The result of s7o.replace (IterF3 ,IterL3 ,IterF4 ,IterL4)
is the string: OPPOOOO.

basic_string::reservebasic_string::reserve

Définit la capacité de la chaîne en fonction d'un nombre au moins aussi grand que le nombre spécifié.Sets the capacity of the string to a number at least as great as a specified number.

void reserve(size_type count = 0);

ParamètresParameters

nombre count
Nombre de caractères pour lequel la mémoire est réservée.The number of characters for which memory is being reserved.

NotesRemarks

Il est important d’avoir une capacité suffisante, car les réallocations sont chronophages et invalident toutes les références, pointeurs et itérateurs qui référencent les caractères d’une chaîne.Having sufficient capacity is important because reallocations is a time-consuming process and invalidates all references, pointers, and iterators that refer to characters in a string.

Le concept de capacité pour les objets de type chaîne est le même que pour les objets de type vecteur.The concept of capacity for objects of type strings is the same as for objects of type vector. Contrairement à Vector, la fonction membre reserve peut être appelée pour réduire la capacité d’un objet.Unlike vector, the member function reserve may be called to shrink the capacity of an object. La demande est non liante, et peut ou ne peut pas se produire.The request is nonbinding and may or may not happen. Comme la valeur par défaut du paramètre est zéro, un appel de reserve est une demande non liée à la réduction de la capacité de la chaîne pour qu’elle corresponde au nombre de caractères actuellement dans la chaîne.As the default value for the parameter is zero, a call of reserve is a non-binding request to shrink the capacity of the string to fit the number of characters currently in the string. La capacité n’est jamais inférieure au nombre actuel de caractères.The capacity is never reduced below the current number of characters.

L’appel à reserve est la seule façon possible de réduire la capacité d’une chaîne.Calling reserve is the only possible way to shrink the capacity of a string. Toutefois, comme indiqué ci-dessus, cette demande est non liante et peut ne pas se produire.However, as noted above, this request is nonbinding and may not happen.

ExempleExample

// basic_string_reserve.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;
   string str1 ("Hello world");
   cout << "The original string str1 is: " << str1 << endl;

   basic_string <char>::size_type sizeStr1, sizerStr1;
   sizeStr1 = str1.size ( );
   basic_string <char>::size_type capStr1, caprStr1;
   capStr1 = str1.capacity ( );

   // Compare size & capacity of the original string
   cout << "The current size of original string str1 is: "
        << sizeStr1 << "." << endl;
   cout << "The capacity of original string str1 is: "
        << capStr1 << "." << endl << endl;

   // Compare size & capacity of the string
   // with added capacity
   str1.reserve ( 40 );
   sizerStr1 = str1.size ( );
   caprStr1 = str1.capacity ( );

   cout << "The string str1with augmented capacity is: "
        << str1 << endl;
   cout << "The current size of string str1 is: "
        << sizerStr1 << "." << endl;
   cout << "The new capacity of string str1 is: "
        << caprStr1 << "." << endl << endl;

   // Compare size & capacity of the string
   // with downsized capacity
   str1.reserve ( );
   basic_string <char>::size_type sizedStr1;
   basic_string <char>::size_type capdStr1;
   sizedStr1 = str1.size ( );
   capdStr1 = str1.capacity ( );

   cout << "The string str1 with downsized capacity is: "
        << str1 << endl;
   cout << "The current size of string str1 is: "
        << sizedStr1 << "." << endl;
   cout << "The reduced capacity of string str1 is: "
        << capdStr1 << "." << endl << endl;
}
The original string str1 is: Hello world
The current size of original string str1 is: 11.
The capacity of original string str1 is: 15.

The string str1with augmented capacity is: Hello world
The current size of string str1 is: 11.
The new capacity of string str1 is: 47.

The string str1 with downsized capacity is: Hello world
The current size of string str1 is: 11.
The reduced capacity of string str1 is: 47.

basic_string::resizebasic_string::resize

Spécifie une nouvelle taille pour une chaîne, en ajoutant ou en effaçant des éléments selon les besoins.Specifies a new size for a string, appending or erasing elements as required.

void resize(
    size_type count,);

void resize(
    size_type count,
    value_type char_value);

ParamètresParameters

nombre count
Nouvelle taille de la chaîne.The new size of the string.

char_valuechar_value
Valeur avec laquelle les caractères ajoutés sont initialisés si des éléments supplémentaires sont nécessaires.The value that appended characters are initialized with if additional elements are required.

NotesRemarks

Si la taille obtenue dépasse le nombre maximal de caractères, le formulaire lève length_error.If the resulting size exceeds the maximum number of characters, the form throws length_error.

ExempleExample

// basic_string_resize.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;
   string  str1 ( "Hello world" );
   cout << "The original string str1 is: " << str1 << endl;

   basic_string <char>::size_type sizeStr1;
   sizeStr1 = str1.size ( );
   basic_string <char>::size_type capStr1;
   capStr1 = str1.capacity ( );

   // Compare size & capacity of the original string
   cout << "The current size of original string str1 is: "
        << sizeStr1 << "." << endl;
   cout << "The capacity of original string str1 is: "
        << capStr1 << "." << endl << endl;

   // Use resize to increase size by 2 elements: exclamations
   str1.resize ( str1.size ( ) + 2 , '!' );
   cout << "The resized string str1 is: " << str1 << endl;

   sizeStr1 = str1.size ( );
   capStr1 = str1.capacity ( );

   // Compare size & capacity of a string after resizing
   cout << "The current size of resized string str1 is: "
        << sizeStr1 << "." << endl;
   cout << "The capacity of resized string str1 is: "
        << capStr1 << "." << endl << endl;

   // Use resize to increase size by 20 elements:
   str1.resize ( str1.size ( ) + 20 );
   cout << "The resized string str1 is: " << str1 << endl;

   sizeStr1 = str1.size ( );
   capStr1 = str1.capacity ( );

   // Compare size & capacity of a string after resizing
   // note capacity increases automatically as required
   cout << "The current size of modified string str1 is: "
        << sizeStr1 << "." << endl;
   cout << "The capacity of modified string str1 is: "
        << capStr1 << "." << endl << endl;

   // Use resize to downsize by 28 elements:
   str1.resize ( str1.size ( ) - 28 );
   cout << "The downsized string str1 is: " << str1 << endl;

   sizeStr1 = str1.size (  );
   capStr1 = str1.capacity (  );

   // Compare size & capacity of a string after downsizing
   cout << "The current size of downsized string str1 is: "
        << sizeStr1 << "." << endl;
   cout << "The capacity of downsized string str1 is: "
        << capStr1 << "." << endl;
}
The original string str1 is: Hello world
The current size of original string str1 is: 11.
The capacity of original string str1 is: 15.

The resized string str1 is: Hello world!!
The current size of resized string str1 is: 13.
The capacity of resized string str1 is: 15.

The resized string str1 is: Hello world!!
The current size of modified string str1 is: 33.
The capacity of modified string str1 is: 47.

The downsized string str1 is: Hello
The current size of downsized string str1 is: 5.
The capacity of downsized string str1 is: 47.

basic_string::reverse_iteratorbasic_string::reverse_iterator

Type qui fournit une référence à un élément stocké dans une chaîne.A type that provides a reference to an element stored in a string.

typedef std::reverse_iterator<iterator> reverse_iterator;

NotesRemarks

Un type reverse_iterator peut servir à changer la valeur d’un caractère. Il sert à itérer au sein d’une chaîne dans l’ordre inverse.A type reverse_iterator can be used to modify the value of a character and is used to iterate through a string in reverse.

ExempleExample

Consultez l’exemple relatif à rbegin pour savoir comment déclarer et utiliser reverse_iterator.See the example for rbegin for an example of how to declare and use reverse_iterator.

basic_string::rfindbasic_string::rfind

Recherche une chaîne vers l'arrière pour trouver la première occurrence d'une sous-chaîne qui correspond à une séquence spécifique de caractères.Searches a string in a backward direction for the first occurrence of a substring that matches a specified sequence of characters.

size_type rfind(
    value_type char_value,
    size_type offset = npos) const;

size_type rfind(
    const value_type* ptr,
    size_type offset = npos) const;

size_type rfind(
    const value_type* ptr,
    size_type offset,
    size_type count) const;

size_type rfind(
    const basic_string<CharType, Traits, Allocator>& str,
    size_type offset = npos) const;

ParamètresParameters

char_valuechar_value
Valeur de caractère que la fonction membre doit rechercher.The character value for which the member function is to search.

décalageoffset
Index de la position à laquelle la recherche doit commencer.Index of the position at which the search is to begin.

\ ptrptr</span> C-string que la fonction membre doit rechercher.The C-string for which the member function is to search.

nombre count
Nombre de caractères, en comptant à partir du premier caractère, dans le C-string que la fonction membre doit rechercher.The number of characters, counting forward from the first character, in the C-string for which the member function is to search.

str str
Chaîne que la fonction membre doit rechercher.The string for which the member function is to search.

Valeur de retourReturn Value

Index de la dernière occurrence, dans une recherche inversée, du premier caractère de la sous-chaîne en cas de réussite ; sinon, npos.The index of the last occurrence, when searched backwards, of the first character of the substring when successful; otherwise npos.

ExempleExample

// basic_string_rfind.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;

   // The first member function
   // searches for a single character in a string
   string str1 ( "Hello Everyone" );
   cout << "The original string str1 is: " << str1 << endl;
   basic_string <char>::size_type indexCh1a, indexCh1b;
   static const basic_string <char>::size_type npos = -1;

   indexCh1a = str1.rfind ( "e" , 9 );
   if ( indexCh1a != npos )
      cout << "The index of the 1st 'e' found before the 9th"
           << " position in str1 is: " << indexCh1a << endl;
   else
      cout << "The character 'e' was not found in str1 ." << endl;

   indexCh1b = str1.rfind ( "x" );
   if ( indexCh1b != npos )
      cout << "The index of the 'x' found in str1 is: "
           << indexCh1b << endl << endl;
   else
      cout << "The character 'x' was not found in str1."
           << endl << endl;

   // The second member function searches a string
   // for a substring as specified by a C-string
   string str2 ( "Let me make this perfectly clear." );
   cout << "The original string str2 is: " << str2 << endl;
   basic_string <char>::size_type indexCh2a, indexCh2b;

   const char *cstr2 = "perfect";
   indexCh2a = str2.rfind ( cstr2 , 30 );
   if ( indexCh2a != npos )
      cout << "The index of the 1st element of 'perfect' "
           << "before\n the 30th position in str2 is: "
           << indexCh2a << endl;
   else
      cout << "The substring 'perfect' was not found in str2 ."
           << endl;

   const char *cstr2b = "imperfectly";
   indexCh2b = str2.rfind ( cstr2b , 30 );
   if ( indexCh2b != npos )
      cout << "The index of the 1st element of 'imperfect' "
           << "before\n the 5th position in str3 is: "
           << indexCh2b << endl;
   else
      cout << "The substring 'imperfect' was not found in str2 ."
           << endl << endl;

   // The third member function searches a string
   // for a substring as specified by a C-string
   string str3 ( "It is a nice day. I am happy." );
   cout << "The original string str3 is: " << str3 << endl;
   basic_string <char>::size_type indexCh3a, indexCh3b;

   const char *cstr3a = "nice";
   indexCh3a = str3.rfind ( cstr3a );
   if ( indexCh3a != npos )
      cout << "The index of the 1st element of 'nice' "
           << "in str3 is: " << indexCh3a << endl;
   else
      cout << "The substring 'nice' was not found in str3 ."
           << endl;

   const char *cstr3b = "am";
   indexCh3b = str3.rfind ( cstr3b , indexCh3a + 25 , 2 );
   if ( indexCh3b != npos )
      cout << "The index of the next occurrance of 'am' in "
           << "str3 begins at: " << indexCh3b << endl << endl;
   else
      cout << "There is no next occurrence of 'am' in str3 ."
           << endl << endl;

   // The fourth member function searches a string
   // for a substring as specified by a string
   string str4 ( "This perfectly unclear." );
   cout << "The original string str4 is: " << str4 << endl;
   basic_string <char>::size_type indexCh4a, indexCh4b;

   string str4a ( "clear" );
   indexCh4a = str4.rfind ( str4a , 15 );
   if (indexCh4a != npos )
      cout << "The index of the 1st element of 'clear' "
           << "before\n the 15th position in str4 is: "
           << indexCh4a << endl;
   else
      cout << "The substring 'clear' was not found in str4 "
           << "before the 15th position." << endl;

   string str4b ( "clear" );
   indexCh4b = str4.rfind ( str4b );
   if ( indexCh4b != npos )
      cout << "The index of the 1st element of 'clear' "
           << "in str4 is: "
           << indexCh4b << endl;
   else
      cout << "The substring 'clear' was not found in str4 ."
           << endl << endl;
}
The original string str1 is: Hello Everyone
The index of the 1st 'e' found before the 9th position in str1 is: 8
The character 'x' was not found in str1.

The original string str2 is: Let me make this perfectly clear.
The index of the 1st element of 'perfect' before
the 30th position in str2 is: 17
The substring 'imperfect' was not found in str2 .

The original string str3 is: It is a nice day. I am happy.
The index of the 1st element of 'nice' in str3 is: 8
The index of the next occurrance of 'am' in str3 begins at: 20

The original string str4 is: This perfectly unclear.
The substring 'clear' was not found in str4 before the 15th position.
The index of the 1st element of 'clear' in str4 is: 17

basic_string::shrink_to_fitbasic_string::shrink_to_fit

Ignore la capacité excédentaire de la chaîne.Discards the excess capacity of the string.

void shrink_to_fit();

NotesRemarks

Cette fonction membre élimine tout stockage inutile dans le conteneur.This member function eliminates any unneeded storage in the container.

basic_string::sizebasic_string::size

Retourne le nombre actuel d'éléments contenus dans une chaîne.Returns the current number of elements in a string.

size_type size() const;

Valeur de retourReturn Value

Longueur de la chaîne.The length of the string.

ExempleExample

// basic_string_size.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;
   string str1 ("Hello world");
   cout << "The original string str1 is: " << str1 << endl;

   // The size and length member functions differ in name only
   basic_string <char>::size_type sizeStr1, lenStr1;
   sizeStr1 = str1.size (  );
   lenStr1 = str1.length (  );

   basic_string <char>::size_type capStr1, max_sizeStr1;
   capStr1 = str1.capacity (  );
   max_sizeStr1 = str1.max_size (  );

   // Compare size, length, capacity & max_size of a string
   cout << "The current size of original string str1 is: "
        << sizeStr1 << "." << endl;
   cout << "The current length of original string str1 is: "
        << lenStr1 << "." << endl;
   cout << "The capacity of original string str1 is: "
        << capStr1 << "." << endl;
   cout << "The max_size of original string str1 is: "
        << max_sizeStr1 << "." << endl << endl;

   str1.erase ( 6, 5 );
   cout << "The modified string str1 is: " << str1 << endl;

   sizeStr1 = str1.size ( );
   lenStr1 = str1.length ( );
   capStr1 = str1.capacity ( );
   max_sizeStr1 = str1.max_size ( );

   // Compare size, length, capacity & max_size of a string
   // after erasing part of the original string
   cout << "The current size of modified string str1 is: "
        << sizeStr1 << "." << endl;
   cout << "The current length of modified string str1 is: "
        << lenStr1 << "." << endl;
   cout << "The capacity of modified string str1 is: "
        << capStr1 << "." << endl;
   cout << "The max_size of modified string str1 is: "
        << max_sizeStr1 << "." << endl;
}

basic_string::size_typebasic_string::size_type

Type entier non signé qui peut représenter le nombre d’éléments et d’index dans une chaîne.An unsigned integer type that can represent the number of elements and indices in a string.

typedef typename allocator_type::size_type size_type;

NotesRemarks

elle est équivalente à allocator_type::size_type.it's equivalent to allocator_type::size_type.

Pour le type string, il est équivalent à size_t.For type string, it's equivalent to size_t.

ExempleExample

// basic_string_size_type.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;
   string str1 ( "Hello world" );

   basic_string <char>::size_type sizeStr1, capStr1;
   sizeStr1 = str1.size (  );
   capStr1 = str1.capacity (  );

   cout << "The current size of string str1 is: "
        << sizeStr1 << "." << endl;
   cout << "The capacity of string str1 is: " << capStr1
         << "." << endl;
}
The current size of string str1 is: 11.
The capacity of string str1 is: 15.

basic_string::substrbasic_string::substr

Copie une sous-chaîne d'un certain nombre de caractères dans une chaîne qui commence à la position spécifiée.Copies a substring of at most some number of characters from a string beginning from a specified position.

basic_string<CharType, Traits, Allocator> substr(
    size_type offset = 0,
    size_type count = npos) const;

ParamètresParameters

décalageoffset
Index situant l’élément à la position à partir de laquelle la copie de la chaîne est effectuée, avec une valeur par défaut égale à 0.An index locating the element at the position from which the copy of the string is made, with a default value of 0.

nombre count
Nombre de caractères qui doivent être copiés s’ils sont présents.The number of characters that are to be copied if they are present.

Valeur de retourReturn Value

Objet de sous-chaîne qui est une copie des éléments de l’opérande de chaîne commençant à la position spécifiée par le premier argument.A substring object that is a copy of elements of the string operand beginning at the position specified by the first argument.

ExempleExample

// basic_string_substr.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;

   string  str1 ("Heterological paradoxes are persistent.");
   cout << "The original string str1 is: \n " << str1
        << endl << endl;

   basic_string <char> str2 = str1.substr ( 6 , 7 );
   cout << "The substring str1 copied is: " << str2
        << endl << endl;

   basic_string <char> str3 = str1.substr (  );
   cout << "The default substring str3 is: \n " << str3
        <<  "\n which is the entire original string." << endl;
}
The original string str1 is:
Heterological paradoxes are persistent.

The substring str1 copied is: logical

The default substring str3 is:
Heterological paradoxes are persistent.
which is the entire original string.

basic_string::swapbasic_string::swap

Échange le contenu de deux chaînes.Exchange the contents of two strings.

void swap(
    basic_string<CharType, Traits, Allocator>& str);

ParamètresParameters

str str
Chaîne source dont les éléments doivent être échangés avec ceux de la chaîne de destination.The source string whose elements are to be exchanged with those in the destination string.

NotesRemarks

Si les chaînes échangées ont le même objet allocateur, la fonction membre swap :If the strings being swapped have the same allocator object, the swap member function:

  • Se produit en temps constant.Occurs in constant time.

  • Ne lève aucune exception.Throws no exceptions.

  • N’invalide aucune référence, pointeur ou itérateur qui désigne des éléments dans les deux chaînes.Invalidates no references, pointers, or iterators that designate elements in the two strings.

Sinon, elle effectue un nombre d’affectations d’éléments et d’appels de constructeurs proportionnel au nombre d’éléments dans les deux séquences contrôlées.Otherwise, it performs a number of element assignments and constructor calls proportional to the number of elements in the two controlled sequences.

ExempleExample

// basic_string_swap.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;

   // Declaring an objects of type basic_string<char>
   string s1 ( "Tweedledee" );
   string s2 ( "Tweedledum" );
   cout << "Before swapping string s1 and s2:" << endl;
   cout << " The basic_string s1 = " << s1 << "." << endl;
   cout << " The basic_string s2 = " << s2 << "." << endl;

   s1.swap ( s2 );
   cout << "After swapping string s1 and s2:" << endl;
   cout << " The basic_string s1 = " << s1 << "." << endl;
   cout << " The basic_string s2 = " << s2 << "." << endl;
}
Before swapping string s1 and s2:
The basic_string s1 = Tweedledee.
The basic_string s2 = Tweedledum.
After swapping string s1 and s2:
The basic_string s1 = Tweedledum.
The basic_string s2 = Tweedledee.

basic_string::traits_typebasic_string::traits_type

Type pour les caractéristiques de caractère des éléments stockés dans une chaîne.A type for the character traits of the elements stored in a string.

typedef Traits traits_type;

NotesRemarks

Le type est un synonyme du deuxième paramètre de modèle Traits.The type is a synonym for the second template parameter Traits.

Pour le type string, il est équivalent à char_traits<char > .For type string, it's equivalent to char_traits<char>.

ExempleExample

Consultez l’exemple relatif à copy pour savoir comment déclarer et utiliser traits_type.See the example for copy for an example of how to declare and use traits_type.

basic_string::value_typebasic_string::value_type

Type qui représente le type des caractères stockés dans une chaîne.A type that represents the type of characters stored in a string.

typedef typename allocator_type::value_type value_type;

NotesRemarks

Elle est équivalente à traits_type::char_type et est équivalente à char pour les objets de type string.It's equivalent to traits_type::char_type and is equivalent to char for objects of type string.

ExempleExample

// basic_string_value_type.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;

   basic_string<char>::value_type ch1 = 'G';

   char ch2 = 'H';

   cout << "The character ch1 is: " << ch1 << "." << endl;
   cout << "The character ch2 is: " << ch2 << "." << endl;
}
The character ch1 is: G.
The character ch2 is: H.

Voir aussiSee also

<string><string>
Sécurité des threads dans la bibliothèque C++ StandardThread Safety in the C++ Standard Library