C++ String Data Type: How std::string Works

How-to basics · Updated November 22, 2026

In C++, the usual string data type is std::string, a standard-library class for storing and working with sequences of characters. Include <string> and write std::string name;; unlike a fixed-size character array, a string can grow as you add text.

What std::string means in C++

std::string is the standard library’s convenient name for std::basic_string<char>. It stores a sequence of char elements and provides operations for finding, joining, comparing, and changing that sequence. The type belongs to the std namespace, so programs commonly use its full name or introduce it with a using declaration.

The word “string” can refer to different things depending on context. In everyday C++ programming, it usually means std::string. A string literal such as "hello", however, is an array of constant characters terminated by a null character. The literal can be used to initialize a std::string, but the two are different types with different behavior.

The standard library also provides related string types. std::wstring uses wchar_t, while std::u8string, std::u16string, and std::u32string use character types intended for specific Unicode encodings. These are not automatically interchangeable with std::string. For ordinary text in many programs, std::string remains the familiar starting point.

Including the header and creating strings

A program needs the standard header <string> to use std::string. Here are several common ways to initialize one:

#include <string>

int main() {
    std::string empty;
    std::string greeting = "Hello";
    std::string repeated(3, '!');
    std::string copy = greeting;
}

The default-constructed string is empty. The literal initializes a string with five characters, the count-and-character constructor creates !!!, and copying creates an independent string value. For example, changing copy afterward does not change greeting.

You may see using namespace std; in short examples, allowing string to be written without the prefix. In larger programs, using std::string explicitly or writing using std::string; helps avoid name conflicts and makes the type’s origin clear.

Size, indexing, and character access

Use size() or its equivalent length() to get the number of stored char elements. These functions return an unsigned size type, std::string::size_type. An empty string has size zero. Use empty() when the question is simply whether the string contains no elements.

std::string word = "cat";
char first = word[0];       // 'c'
word[1] = 'u';              // word is now "cut"
std::size_t count = word.size();

Square-bracket indexing starts at zero, so the last valid index is size() - 1 when the string is not empty. Accessing an invalid index with operator[] does not provide the checked-access guarantee that at() does. Calling at() with an out-of-range index throws std::out_of_range. Choose checked access when detecting an invalid index is more important than avoiding that check.

A char is one element of the string, not necessarily one human-visible character. That distinction matters for accented letters, emoji, and other text encoded using multiple bytes; a later section explains it.

Changing, joining, and searching text

Strings support familiar operations that make basic text handling direct. The += operator appends text, while append() is an equivalent explicit option. The plus operator creates a combined string. Use insert(), erase(), or replace() when changing part of an existing value.

std::string message = "Good";
message += " morning";
message.insert(4, ",");
message.replace(0, 4, "Hello");
// message is "Hello, morning"

For the example, insert(4, ",") puts a comma before the space, and replace(0, 4, "Hello") replaces the four characters at the beginning. Positions and lengths are counted in string elements, not words or display columns.

To search, use find(). It returns the position of the first match, or std::string::npos if it cannot find one. Compare against that named value rather than assuming a particular numeric “not found” result:

std::string line = "red, green, blue";
auto position = line.find("green");
if (position != std::string::npos) {
    line.replace(position, 5, "gold");
}

String comparisons such as == and < compare sequences of elements. They do not perform language-aware sorting or determine whether two differently encoded spellings look identical on screen.

Reading and printing strings

Include <iostream> to use the standard input and output streams. The extraction expression std::cin >> name reads a whitespace-delimited token: it stops at spaces, tabs, or a newline. That is appropriate for a username or single word, but not for a full name or sentence.

Use std::getline to read a whole line, including spaces up to the newline:

#include <iostream>
#include <string>

int main() {
    std::string sentence;
    std::getline(std::cin, sentence);
    std::cout << sentence << '\n';
}

A common input surprise occurs when a program first uses >> and then calls getline. The newline left behind by the token-reading operation can be consumed immediately, making the line appear empty. When that transition is intentional, discard the rest of the current line with std::getline(std::cin, ignored) before reading the next full line; declare ignored as a string. More elaborate input handling may be needed if the input can contain more than a newline after the token.

std::string and C-style character arrays

A C-style string is conventionally a sequence of characters ending with a null character, written '\0'. Functions in the C string library, such as std::strlen, look for that terminator. A std::string manages its own length, can grow, and provides member functions, so it is usually easier and safer for ordinary C++ text work.

There are still times when an interface requires a null-terminated character sequence. The c_str() member function returns a pointer to such a sequence for use with APIs that expect one. The pointer is owned by the string; do not delete it, and do not rely on it remaining valid after operations that modify the string. Consult the API’s requirements when passing it to a function that stores the pointer.

A string can also contain an embedded null character. Its size() still reports the full number of elements, but a C function that expects a null-terminated string will treat the first embedded null as the end. This is one reason a pointer alone does not always communicate the full length of a std::string value.

Unicode and what string length counts

std::string stores char elements; it does not itself define a character encoding. Text from a file, network protocol, or other source must be interpreted according to that source’s encoding. UTF-8 is widely used, and a UTF-8 sequence for one visible character may take several char elements. Consequently, size() reports bytes for UTF-8 text, not necessarily the number of Unicode code points or user-perceived characters.

For example, a character such as “é” may be represented in UTF-8 as more than one byte. A string operation that indexes or erases one element can therefore split an encoded character if it is applied at the wrong byte position. Emoji and combined characters can be more complex still: a single displayed symbol may consist of multiple code points.

Choose a strategy based on the work the program must do:

  • For ASCII text or data whose encoding is explicitly handled elsewhere, std::string is often sufficient.
  • For UTF-8 storage and transport, std::string can hold the bytes, but Unicode-aware iteration, validation, normalization, or case conversion requires suitable additional logic or a library.
  • Do not assume that std::wstring automatically solves Unicode processing. The width and encoding of wchar_t vary by platform, and wide strings still need well-defined encoding rules.

Encoding is a common source of bugs because text can look correct while its bytes differ. When comparing or exchanging text, identify the encoding expected at each boundary rather than treating a string’s type as proof of its encoding.

Memory, performance, and string_view

A std::string owns its character storage and manages memory as its contents change. Since C++11, its character elements are stored contiguously, which supports access through data() and interoperability with APIs that accept a character pointer. The standard does not require a particular internal layout or a particular small-string optimization, so code should not depend on implementation-specific storage details.

Repeatedly appending text may cause the string to obtain more capacity. capacity() reports how many elements can fit before a reallocation is required, and reserve(n) can request capacity for at least a chosen number of elements. Reserving can be useful when the expected size is known, but it is not necessary for every short string. Reallocation can invalidate pointers, references, and iterators referring to the string’s elements, so avoid keeping them across modifications unless their validity is guaranteed.

For a large number of pieces, building a result with repeated concatenation can involve avoidable copying in some patterns. Appending into one destination string, or reserving an estimate when it is practical, can make the intent and allocation behavior clearer. Measure performance before complicating code: the best choice depends on the workload and library implementation.

C++17 also provides std::string_view in <string_view>. It is a non-owning view of a sequence of characters, useful for reading or passing text without copying in suitable interfaces. Unlike std::string, it does not own the characters or guarantee their lifetime. A view that outlives the underlying string can dangle, so use an owning string when the data must be retained.

Common mistakes to avoid

  • Forgetting the header or namespace: include <string> and use std::string, unless an appropriate using declaration is present.
  • Expecting formatted input to read a sentence: std::cin >> text stops at whitespace; use std::getline for a full line.
  • Confusing bytes with visible characters: UTF-8 characters can occupy multiple elements, so byte indexing is not general-purpose character indexing.
  • Using a pointer after changing its string: modifications can invalidate pointers or references to the character storage.
  • Assuming a string is always null-terminated in the C-string sense: use c_str() when an API explicitly requires a null-terminated pointer, and account for embedded nulls.

Frequently Asked Questions

Is string a built-in data type in C++?

No. std::string is a class type supplied by the C++ standard library, rather than a built-in language type like int. It is available by including <string>.

What is the difference between string and char in C++?

char stores one character-sized element. std::string stores a sequence of such elements and manages the sequence’s size and storage. A string may contain many char elements, including zero of them.

How do I compare two strings in C++?

Use operators such as ==, !=, and < to compare their stored sequences. These comparisons are not case-insensitive and do not provide locale-aware or Unicode-normalized comparison by themselves.

How do I get the length of a string in C++?

Call size() or length(); both return the number of stored elements. For UTF-8 text, that count is bytes, not necessarily visible characters.

Should I use std::string or a char array?

Prefer std::string for most text you create, edit, or store in C++. Use a character array or pointer when a particular interface requires it, or when working with a low-level format that explicitly uses null-terminated character sequences.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.