C++ Strings

The basic_string class provides a useful way to manipulate and store sequences of characters. It is defined as a basic template class in the std namespace in the <string> header file.

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

The C++ standard library provides two specializations of class basic_string.

 typedef basic_string<char>    string;
 typedef basic_string<wchar_t> wstring;

In the following sections, string means any specialization of class basic_string, and Char means its character type.

Constructorscreate strings from arrays of characters and other strings
Operatorsconcatenate strings, assign strings, use strings for I/O, compare strings
appendappend characters and strings onto a string
assigngive a string values from strings of characters and other C++ strings
atreturns the character at a specific location
beginreturns an iterator to the beginning of the string
c_strreturns a non-modifiable standard C character array version of the string
capacityreturns the number of characters that the string can hold
clearremoves all characters from the string
comparecompares two strings
copycopies characters from a string into an array
datareturns a pointer to the first character of a string
emptytrue if the string has no characters
endreturns an iterator just past the last character of a string
eraseremoves characters from a string
findfind characters in the string
find_first_not_offind first absence of characters
find_first_offind first occurrence of characters
find_last_not_offind last absence of characters
find_last_offind last occurrence of characters
getlineread data from an I/O stream into a string
insertinsert characters into a string
lengthreturns the length of the string
max_sizereturns the maximum number of characters that the string can hold
nposa special value that indicates “not found” or “all remaining characters”
push_backadd a character to the end of the string
rbeginreturns a reverse_iterator to the end of the string
rendreturns a reverse_iterator to the beginning of the string
replacereplace characters in the string
reservesets the minimum capacity of the string
resizechange the size of the string
rfindfind the last occurrence of a substring
sizereturns the number of items in the string
substrreturns a certain substring
swapswap the contents of this string with another