String (C++)

From Wikipedia, the free encyclopedia
Jump to: navigation, search

In the C++ programming language, the std::string class is a standard representation for a text string. This class alleviates many of the problems introduced by C-style strings by putting the onus of memory ownership on the string class rather than on the programmer, and allowing the NUL byte to be in the string. The class provides some typical string operations like comparison, concatenation, find and replace, and a function for obtaining substrings. It can be constructed from a C-style string, and a C-style string can also be obtained from it.

The individual units making up the string are C char, at least (and almost always) 8 bits each. In modern usage these are often not "characters", but parts of a multibyte character encoding such as UTF-8.

Overview of functions[edit]

    • string::string(constructor) – Constructs the string from variety of sources
    • string::~string(destructor) – Destructs the string
    • string::operator= – Replace the string
    • string::assign – Replace the string
    • string::get_allocator – Returns the allocator used to allocate memory for the bytes
  • Byte access
    • string::at – Accesses specified byte with bounds checking.
    • string::operator[] – Accesses specified byte
    • string::front – Accesses the first byte
    • string::back – Accesses the last byte
    • string::data – Accesses the underlying array
  • Iterators
    • string::begin – Returns an iterator to the beginning of the string
    • string::end – Returns an iterator to the end of the string
    • string::rbegin – Returns a reverse iterator to the reverse beginning of the string
    • string::rend – Returns a reverse iterator to the reverse end of the string
  • Capacity
    • string::empty – Checks whether the string is empty
    • string::size – Returns the number of bytes in the string.
    • string::max_size – Returns the maximum possible number of bytes in the string.
    • string::reserve – Reserves storage in the string
    • string::capacity – Returns the current reservation
    • string::shrink_to_fit (C++11) – Reduces memory usage by freeing unused memory
  • Modifiers
    • string::clear – Clears the contents
    • string::insert – Inserts bytes or strings
    • string::erase – Deletes bytes
    • string::push_back – Appends a byte
    • string::append – Appends bytes or strings
    • string::operator+= – Appends
    • string::pop_back – Removes the last byte
    • string::resize – Changes the number of stored bytes
    • string::swap – Swaps the contents with another string
    • ...
  • Search
    • ...


#include <iostream>
#include <string>
using namespace std;

int main()
    string foo = "fighters";
    string bar = "stool";

    // "!=" compares string contents for inequality, even though they are different objects.
    if (foo != bar)
        cout << "The strings are different." << endl;

    // Prints "stool fighters" by creating a temporary object, which is automatically freed.
    cout << bar + " " + foo << endl;

    return 0;

As operator[] returns a non-const reference to one of the bytes, which can be used to modify the string at any later time, it is almost impossible to correctly implement std::string with shared byte arrays on popular computer architectures, therefore all modern implementations have a copy of the byte array per string. Due to this, copying a string may take as long as O(n) (i.e., copying takes time proportional to the length of the string). It will also cause heap memory to be allocated, which is usually far more expensive than the copy.

For that reason, string is generally passed by reference-to-const to avoid unnecessary copying:

void print_the_string(const string& str)
    cout << str;

To interoperate with C-interfaces, it is often necessary to obtain a null terminated string from a basic_string. The c_str() member function yields a pointer to the first element of an array whose elements correspond to the bytes in the original string and this array has a 0 at the offset of the length. If the null terminator is not needed, the data() method returns the pointer without any work needed to make sure the 0 is there. If the string is modified or its lifetime ends, the pointers returned by these methods become invalid.

Related classes[edit]

std::string is a typedef for a particular instantiation of the std::basic_string class template.[1] Its definition is found in the <string> header:

typedef basic_string<char> string;

Thus std::string provides std::basic_string functionality for strings consisting of the C char.

There is a similar class std::wstring, which consists of wchar_t, and is most often used to store UTF-16 text on Windows and UTF-32 on most Unix-like platforms. As the difference between these made writing portable code that shared data structures impossible, C++11 added two new classes: std::u16string and std::u32string (made up of the new types char16_t and char32_t), which are the given number of bits per code unit on all platforms.[2]

A std::basic_string is guaranteed to be valid for any type with a std::char_traits struct to accompany it. As of C++11, only char, wchar_t, char16_t, and char32_t specializations are required to be implemented in the standard library; any other types are implementation-defined.[3] They are also a Standard Library container, and thus the functions in the Standard Library Algorithms can be applied to the code units in strings, though these are of limited use as they rarely deal with sequences or patterns of items.


  1. ^ "C++ reference for basic_string". Retrieved 11 January 2011. 
  2. ^ "C++11 Paper N3336". Open Standards. Programming Language C++, Library Working Group. 13 Jan 2012. Retrieved 2 Nov 2013. 
  3. ^ "char_traits - C++ Reference". Retrieved 2015-08-01.