Skip to main content
caution

Note, this article is not finished! You can help by editing this doc page.

Overview

template< class CharT, /* ... */ >
class basic_string;

A class that is used to store and manipulate sequence of characters.

Memory

The elements of a string are stored contiguously in memory. This means that a pointer to an element of a string may be passed to any function that expects a pointer to an element of an array of characters.

String elements in memory

Aliases

Type std::string is in fact an alias to: std::basic_string<char>.

Available std::basic_string aliases
pubstd::stringstd::basic_string<char>
pubstd::wstringstd::basic_string<wchar_t>
pubstd::u8string (since C++20)std::basic_string<char8_t>
pubstd::u16string (since C++11)std::basic_string<char16_t>
pubstd::u32string (since C++11)std::basic_string<char32_t>
pubstd::pmr::string (since C++17)std::pmr::basic_string<char>
pubstd::pmr::wstring (since C++17)std::pmr::basic_string<wchar_t>
pubstd::pmr::u8string (since C++20)std::pmr::basic_string<char8_t>
pubstd::pmr::u16string (since C++17)std::pmr::basic_string<char16_t>
pubstd::pmr::u32string (since C++17)std::pmr::basic_string<char32_t>

Technical details

Technical definition of a string

The class template basic_string stores and manipulates sequences of char-like objects, which are non-array objects of trivial standard-layout type. The class is dependent neither on the character type nor on the nature of operations on that type.

The definitions of the operations are supplied via the Traits template parameter - a specialization of std::char_traits or a compatible traits class. Traits::char_type and CharT must name the same type; otherwise the program is ill-formed

.

The elements of a basic_string are stored contiguously, that is, for a basic_string s, &*(s.begin() + n) == &*s.begin() + n for any n in [ 0, s.size() ), or, equivalently, a pointer to s[0] can be passed to functions that expect a pointer to the first element of a null-terminated (since C++11) CharT[] array.

std::basic_string

Defined instring

Template parameters

pubCharTA character type.
pubTraitsTraits class specifying the operations on the character type.
pubAllocatorAllocator type used to allocate internal storage.

Type names

pubtraits_typeTraits
pubvalue_typeCharT
puballocator_typeAllocator
pubsize_typeAllocator::size_type (until C++11)
std::allocator_traits<Allocator>::size_type (since C++11)
pubdifference_typeAllocator::difference_type (until C++11)
std::allocator_traits<Allocator>::difference_type (since C++11)
pubreferencevalue_type&
pubconst_referencevalue_type const&
pubpointerAllocator::pointer (until C++11)
std::allocator_traits<Allocator>::pointer (since C++11)
pubconst_pointerAllocator::const_pointer (until C++11)
std::allocator_traits<Allocator>::const_pointer (since C++11)
pubiterator

LegacyRandomAccessIterator and  LegacyContiguousIterator to value_type 

 (since C++20)

LegacyRandomAccessIterator and  LegacyConstexprIterator and  contiguous_iterator to value_type 

 (since C++20)
pubreverse_iteratorstd::reverse_iterator<iterator>
pubconst_reverse_iteratorstd::reverse_iterator<const_iterator>

Member functions

pub(constructors)

Constructs a basic_string.

pub(destructor)

Destroys the string, deallocating internal storage if used.

puboperator=

Assigns values to the string.

pubassign

Assigns characters to the string.

pubget_allocator

Returns the associated allocator.

Element access

pubat

Accesses the specified character with bounds checking.

puboperator[]

Accesses the specified character.

pubfront (since C++11)

Returns the first character.

pubback (since C++11)

Returns the last character.

pubdata

Returns a pointer to the first character of a string.

pubc_str

Returns a non-modifiable standard C character array version of the string.

puboperator basic_string_view (since C++17)

Returns a non-modifiable string_view into the entire string.

Iterators

pubbegin
cbegin (since C++11)

Returns an iterator/const_iterator to the beginning.

pubend
cend (since C++11)

Returns an iterator/const_iterator to the end.

pubrbegin
crbegin (since C++11)

Returns an reverse iterator/const_iterator to the beginning.

pubrend
crend (since C++11)

Returns an reverse iterator/const_iterator to the end.

Capacity

pubempty

Returns true if the string is empty, otherwise false.

pubsize
length

Returns the number of characters.

pubmax_size

Returns the maximum number of characters.

pubreserve

Reserves storage

pubcapacity

Returns the number of characters that can be held in currently allocated storage

pubshrink_to_fit (since C++11)

Reduces memory usage by freeing unused memory.

Operations

pubclear

Clears the contents.

pubinsert

Inserts characters.

puberase

Removes characters.

pubpush_back

Appends a character to the end.

pubpop_back (since C++11)

Removes the last character.

pubappend

Appends characters to the end.

puboperator+=

Appends characters to the end.

pubcompare

Compares two strings.

pubstarts_with (since C++20)

Checks if the string starts with the given prefix.

pubends_with (since C++20)

Checks if the string ends with the given suffix.

pubcontains (since C++23)

Checks if the string contains the given substring or character.

pubreplace

Replaces specified portion of a string.

pubsubstr

Returns a substring.

pubcopy

Copies characters.

pubresize

Changes the number of characters stored.

pubresize_and_overwrite (since C++23)

Changes the number of characters stored and possibly overwrites indeterminate contents via user-provided operation.

pubswap

Swaps the contents.

pubfind

Find characters in the string.

pubrfind

Find the last occurrence of a substring.

pubfind_first_of

Find first occurrence of characters.

pubfind_first_not_of

Find first absence of characters.

pubfind_last_of

Find last occurrence of characters.

pubfind_last_not_of

Find last absence of characters.

Constants

pubstaticconstexprnpos

A special value. The exact meaning depends on the context.

Non-member functions

puboperator+

Concatenates two strings or a string and a char.

puboperator==
operator!=  (removed in C++20)
operator<  (removed in C++20)
operator>  (removed in C++20)
operator<=  (removed in C++20)
operator>=  (removed in C++20)
operator<=>

Lexicographically compares two strings.

pubstd::swap (std::basic_string)

An overload for a std::swap algorithm.

puberase (std::basic_string)
erase_if (std::basic_string)

Overloads for std::erase/std::erase_if algorithms.

Input/output

puboperator<<
operator>>

Performs stream input and output on strings.

pubgetline

Read data from an I/O stream into a string.

Numeric conversions

pubstoi
stol
stoll

Converts a string to a signed integer.

pubstoui
stoul
stoull

Converts a string to an unsigned integer.

pubstof
stod
stold

Converts a string to a floating point value.

pubto_string

Converts an integral or floating point value to std::string.

pubto_wstring

Converts an integral or floating point value to std::wstring.

Literals

Defined in namespace std::literals::string_literals
puboperator ""s

Converts a character array literal to std::string.

Helper classes

pub std::hash<std::string>  (since C++11)
std::hash<std::u8string>  (since C++20)
std::hash<std::u16string>  (since C++11)
std::hash<std::u32string>  (since C++11)
std::hash<std::wstring>  (since C++11)
std::hash<std::pmr::string>  (since C++17)
std::hash<std::pmr::u8string>  (since C++20)
std::hash<std::pmr::u16string>  (since C++17)
std::hash<std::pmr::u32string>  (since C++17)
std::hash<std::pmr::wstring>  (since C++17)

Specializations for std::hash to support string hashing.

Deduction guides (since C++17)

Click to expand

Deduction guides

// (1)
template< class InputIt, class Alloc = std::allocator<
typename std::iterator_traits<InputIt>::value_type> >
basic_string( InputIt, InputIt, Alloc = Alloc() )
-> basic_string<typename std::iterator_traits<InputIt>::value_type,
std::char_traits<typename std::iterator_traits<InputIt>::value_type>,
Alloc>;

(1) allows deduction from a iterator range

// (2)
template< class CharT,
class Traits,
class Alloc = std::allocator<CharT> >
explicit basic_string( std::basic_string_view<CharT, Traits>, const Alloc& = Alloc() )
-> basic_string<CharT, Traits, Alloc>;
// (3)
template< class CharT,
class Traits,
class Alloc = std::allocator<CharT>> >
basic_string( std::basic_string_view<CharT, Traits>, typename /*see below*/::size_type,
typename /*see below*/::size_type, const Alloc& = Alloc() )
-> basic_string<CharT, Traits, Alloc>;

(2) and (3) allow deduction from a std::basic_string_view<CharT, Traits>

The size_type parameter type refers to the size_type member type of the type deduced by the deduction guide.

Overload resolution

In order for any of the deduction guides to participate in overload resolution, the folllowing requirements must be met:

note

The extent to which the library determines that a type does not satisfy LegacyInputIterator is unspecified, except that as a minimum:

  • Integral types do not qualify as input iterators.

Likewise, the extent to which it determines that a type does not satisfy Allocator is unspecified, except that as a minimum:

Examples

Basic manipulation

Creating and printing a simple string
#include <iostream>
#include <string>

int main()
{
std::string s = "World";
std::cout << "Hello, " << s << "!" << std::endl;
}
Result
Hello, World!
Concatenating strings
#include <iostream>
#include <string>

int main()
{
std::string a = "Hello, ";
std::string b = "World!";
std::string c = a + b;
std::cout << c;
}
Result
Hello, World!
Splitting a string
#include <iostream>
#include <string>

int main()
{
// Split by the comma.
// v
std::string a = "Hello, World!";
size_t pos = a.find(',');

std::string hello = a.substr(0, pos);
// 1 for a comma, and 1 for a space before "World"
std::string world = a.substr(pos + 1 + 1);

std::cout << hello << '\n' << world;
}
Result
Hello
World!

Conversions

Convert a string to int
#include <iostream>
#include <string>

int main()
{
std::string numberInString = "8314";

// Note: stoi can throw exception if failed!
int number = std::stoi(numberInString);
std::cout << "Number: " << number;
}
Result
Number: 8314
Convert string to float
#include <iostream>
#include <string>

int main()
{
std::string numberInString = "3.141";

// Note: stof can throw exception if failed!
float number = std::stof(numberInString);
std::cout << "Number: " << number;
}
Result
Number: 3.141

Convert numbers to std::string

Convert string to float
#include <iostream>
#include <string>

int main()
{
std::string numberInString = "3.141";

// Note: stof can throw exception if failed!
float number = std::stof(numberInString);
std::cout << "Number: " << number;
}
Possible output
s1: 123
s2: 456.200012
s3: 3.141590
tip

If you want a custom formatting, use std::stringstream, or a non-standard library fmtlib.

This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.
caution

Note, this article is not finished! You can help by editing this doc page.

Overview

template< class CharT, /* ... */ >
class basic_string;

A class that is used to store and manipulate sequence of characters.

Memory

The elements of a string are stored contiguously in memory. This means that a pointer to an element of a string may be passed to any function that expects a pointer to an element of an array of characters.

String elements in memory

Aliases

Type std::string is in fact an alias to: std::basic_string<char>.

Available std::basic_string aliases
pubstd::stringstd::basic_string<char>
pubstd::wstringstd::basic_string<wchar_t>
pubstd::u8string (since C++20)std::basic_string<char8_t>
pubstd::u16string (since C++11)std::basic_string<char16_t>
pubstd::u32string (since C++11)std::basic_string<char32_t>
pubstd::pmr::string (since C++17)std::pmr::basic_string<char>
pubstd::pmr::wstring (since C++17)std::pmr::basic_string<wchar_t>
pubstd::pmr::u8string (since C++20)std::pmr::basic_string<char8_t>
pubstd::pmr::u16string (since C++17)std::pmr::basic_string<char16_t>
pubstd::pmr::u32string (since C++17)std::pmr::basic_string<char32_t>

Technical details

Technical definition of a string

The class template basic_string stores and manipulates sequences of char-like objects, which are non-array objects of trivial standard-layout type. The class is dependent neither on the character type nor on the nature of operations on that type.

The definitions of the operations are supplied via the Traits template parameter - a specialization of std::char_traits or a compatible traits class. Traits::char_type and CharT must name the same type; otherwise the program is ill-formed

.

The elements of a basic_string are stored contiguously, that is, for a basic_string s, &*(s.begin() + n) == &*s.begin() + n for any n in [ 0, s.size() ), or, equivalently, a pointer to s[0] can be passed to functions that expect a pointer to the first element of a null-terminated (since C++11) CharT[] array.

std::basic_string

Defined instring

Template parameters

pubCharTA character type.
pubTraitsTraits class specifying the operations on the character type.
pubAllocatorAllocator type used to allocate internal storage.

Type names

pubtraits_typeTraits
pubvalue_typeCharT
puballocator_typeAllocator
pubsize_typeAllocator::size_type (until C++11)
std::allocator_traits<Allocator>::size_type (since C++11)
pubdifference_typeAllocator::difference_type (until C++11)
std::allocator_traits<Allocator>::difference_type (since C++11)
pubreferencevalue_type&
pubconst_referencevalue_type const&
pubpointerAllocator::pointer (until C++11)
std::allocator_traits<Allocator>::pointer (since C++11)
pubconst_pointerAllocator::const_pointer (until C++11)
std::allocator_traits<Allocator>::const_pointer (since C++11)
pubiterator

LegacyRandomAccessIterator and  LegacyContiguousIterator to value_type 

 (since C++20)

LegacyRandomAccessIterator and  LegacyConstexprIterator and  contiguous_iterator to value_type 

 (since C++20)
pubreverse_iteratorstd::reverse_iterator<iterator>
pubconst_reverse_iteratorstd::reverse_iterator<const_iterator>

Member functions

pub(constructors)

Constructs a basic_string.

pub(destructor)

Destroys the string, deallocating internal storage if used.

puboperator=

Assigns values to the string.

pubassign

Assigns characters to the string.

pubget_allocator

Returns the associated allocator.

Element access

pubat

Accesses the specified character with bounds checking.

puboperator[]

Accesses the specified character.

pubfront (since C++11)

Returns the first character.

pubback (since C++11)

Returns the last character.

pubdata

Returns a pointer to the first character of a string.

pubc_str

Returns a non-modifiable standard C character array version of the string.

puboperator basic_string_view (since C++17)

Returns a non-modifiable string_view into the entire string.

Iterators

pubbegin
cbegin (since C++11)

Returns an iterator/const_iterator to the beginning.

pubend
cend (since C++11)

Returns an iterator/const_iterator to the end.

pubrbegin
crbegin (since C++11)

Returns an reverse iterator/const_iterator to the beginning.

pubrend
crend (since C++11)

Returns an reverse iterator/const_iterator to the end.

Capacity

pubempty

Returns true if the string is empty, otherwise false.

pubsize
length

Returns the number of characters.

pubmax_size

Returns the maximum number of characters.

pubreserve

Reserves storage

pubcapacity

Returns the number of characters that can be held in currently allocated storage

pubshrink_to_fit (since C++11)

Reduces memory usage by freeing unused memory.

Operations

pubclear

Clears the contents.

pubinsert

Inserts characters.

puberase

Removes characters.

pubpush_back

Appends a character to the end.

pubpop_back (since C++11)

Removes the last character.

pubappend

Appends characters to the end.

puboperator+=

Appends characters to the end.

pubcompare

Compares two strings.

pubstarts_with (since C++20)

Checks if the string starts with the given prefix.

pubends_with (since C++20)

Checks if the string ends with the given suffix.

pubcontains (since C++23)

Checks if the string contains the given substring or character.

pubreplace

Replaces specified portion of a string.

pubsubstr

Returns a substring.

pubcopy

Copies characters.

pubresize

Changes the number of characters stored.

pubresize_and_overwrite (since C++23)

Changes the number of characters stored and possibly overwrites indeterminate contents via user-provided operation.

pubswap

Swaps the contents.

pubfind

Find characters in the string.

pubrfind

Find the last occurrence of a substring.

pubfind_first_of

Find first occurrence of characters.

pubfind_first_not_of

Find first absence of characters.

pubfind_last_of

Find last occurrence of characters.

pubfind_last_not_of

Find last absence of characters.

Constants

pubstaticconstexprnpos

A special value. The exact meaning depends on the context.

Non-member functions

puboperator+

Concatenates two strings or a string and a char.

puboperator==
operator!=  (removed in C++20)
operator<  (removed in C++20)
operator>  (removed in C++20)
operator<=  (removed in C++20)
operator>=  (removed in C++20)
operator<=>

Lexicographically compares two strings.

pubstd::swap (std::basic_string)

An overload for a std::swap algorithm.

puberase (std::basic_string)
erase_if (std::basic_string)

Overloads for std::erase/std::erase_if algorithms.

Input/output

puboperator<<
operator>>

Performs stream input and output on strings.

pubgetline

Read data from an I/O stream into a string.

Numeric conversions

pubstoi
stol
stoll

Converts a string to a signed integer.

pubstoui
stoul
stoull

Converts a string to an unsigned integer.

pubstof
stod
stold

Converts a string to a floating point value.

pubto_string

Converts an integral or floating point value to std::string.

pubto_wstring

Converts an integral or floating point value to std::wstring.

Literals

Defined in namespace std::literals::string_literals
puboperator ""s

Converts a character array literal to std::string.

Helper classes

pub std::hash<std::string>  (since C++11)
std::hash<std::u8string>  (since C++20)
std::hash<std::u16string>  (since C++11)
std::hash<std::u32string>  (since C++11)
std::hash<std::wstring>  (since C++11)
std::hash<std::pmr::string>  (since C++17)
std::hash<std::pmr::u8string>  (since C++20)
std::hash<std::pmr::u16string>  (since C++17)
std::hash<std::pmr::u32string>  (since C++17)
std::hash<std::pmr::wstring>  (since C++17)

Specializations for std::hash to support string hashing.

Deduction guides (since C++17)

Click to expand

Deduction guides

// (1)
template< class InputIt, class Alloc = std::allocator<
typename std::iterator_traits<InputIt>::value_type> >
basic_string( InputIt, InputIt, Alloc = Alloc() )
-> basic_string<typename std::iterator_traits<InputIt>::value_type,
std::char_traits<typename std::iterator_traits<InputIt>::value_type>,
Alloc>;

(1) allows deduction from a iterator range

// (2)
template< class CharT,
class Traits,
class Alloc = std::allocator<CharT> >
explicit basic_string( std::basic_string_view<CharT, Traits>, const Alloc& = Alloc() )
-> basic_string<CharT, Traits, Alloc>;
// (3)
template< class CharT,
class Traits,
class Alloc = std::allocator<CharT>> >
basic_string( std::basic_string_view<CharT, Traits>, typename /*see below*/::size_type,
typename /*see below*/::size_type, const Alloc& = Alloc() )
-> basic_string<CharT, Traits, Alloc>;

(2) and (3) allow deduction from a std::basic_string_view<CharT, Traits>

The size_type parameter type refers to the size_type member type of the type deduced by the deduction guide.

Overload resolution

In order for any of the deduction guides to participate in overload resolution, the folllowing requirements must be met:

note

The extent to which the library determines that a type does not satisfy LegacyInputIterator is unspecified, except that as a minimum:

  • Integral types do not qualify as input iterators.

Likewise, the extent to which it determines that a type does not satisfy Allocator is unspecified, except that as a minimum:

Examples

Basic manipulation

Creating and printing a simple string
#include <iostream>
#include <string>

int main()
{
std::string s = "World";
std::cout << "Hello, " << s << "!" << std::endl;
}
Result
Hello, World!
Concatenating strings
#include <iostream>
#include <string>

int main()
{
std::string a = "Hello, ";
std::string b = "World!";
std::string c = a + b;
std::cout << c;
}
Result
Hello, World!
Splitting a string
#include <iostream>
#include <string>

int main()
{
// Split by the comma.
// v
std::string a = "Hello, World!";
size_t pos = a.find(',');

std::string hello = a.substr(0, pos);
// 1 for a comma, and 1 for a space before "World"
std::string world = a.substr(pos + 1 + 1);

std::cout << hello << '\n' << world;
}
Result
Hello
World!

Conversions

Convert a string to int
#include <iostream>
#include <string>

int main()
{
std::string numberInString = "8314";

// Note: stoi can throw exception if failed!
int number = std::stoi(numberInString);
std::cout << "Number: " << number;
}
Result
Number: 8314
Convert string to float
#include <iostream>
#include <string>

int main()
{
std::string numberInString = "3.141";

// Note: stof can throw exception if failed!
float number = std::stof(numberInString);
std::cout << "Number: " << number;
}
Result
Number: 3.141

Convert numbers to std::string

Convert string to float
#include <iostream>
#include <string>

int main()
{
std::string numberInString = "3.141";

// Note: stof can throw exception if failed!
float number = std::stof(numberInString);
std::cout << "Number: " << number;
}
Possible output
s1: 123
s2: 456.200012
s3: 3.141590
tip

If you want a custom formatting, use std::stringstream, or a non-standard library fmtlib.

This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.