Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 171 ยท Strings

Strings with std::string

Learn C++ std::string from scratch, creating and joining strings, size and length, indexing with [] and at(), comparing, and looping over text.

Text is everywhere: names, messages, file paths, commands, JSON. In modern C++ you handle text with std::string, a class from the <string> header that owns a sequence of characters, grows and shrinks as needed, and cleans up after itself. You never have to allocate memory or worry about a terminating null character the way C programmers do.

This lesson covers the essentials: creating strings, joining them, measuring them, reading and changing individual characters, comparing them and looping over them. If you've used Java, C# or Python, pay attention to one big difference: C++ strings are mutable. You can change a character in place, and a copy of a string is a real, independent copy.

Creating strings

Include <string> and create a std::string like any other variable. There are several useful ways to initialize one:

C++ Ways to create a std::string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

A default-constructed std::string is always a valid empty string, unlike an uninitialized int. Watch out for one subtle difference: std::string line(12, '=') with parentheses means "12 copies of =", while std::string line{12, '='} with braces would create a two-character string from the list of characters 12 and =. For strings, use parentheses for the count form.

String literals are not std::string

A literal like "Lisbon" is not a std::string. It's an array of const char (a C-style string, covered in C-Style Strings). It converts to std::string automatically when you initialize or assign one, but this matters with auto:

C++
auto a = "hello";          // const char*, NOT std::string
auto b = std::string{"hello"};  // std::string

using namespace std::string_literals;
auto c = "hello"s;         // std::string, thanks to the s suffix

The s suffix (C++14) creates a std::string directly. It lives in the namespace std::string_literals, and pulling just that namespace in with using namespace is fine, even though using namespace std; is not recommended (see C++ Syntax).

Joining strings: + and +=

The + operator concatenates two strings into a new one, and += appends to an existing string. Both work with std::string, string literals and single characters, as long as at least one side of each + is a std::string:

C++ Concatenation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

first + " " + last works because + groups left to right: first + " " is a std::string, and adding last to it is fine. Two literals alone can't be added, though:

C++
std::string a = "Hello, " + "world";        // error: you can't add two pointers
std::string b = std::string("Hello, ") + "world";   // OK
std::string c = "Hello, " "world";          // OK: adjacent literals are joined by the compiler

Never add a number to a string literal. "Score: " + 5 compiles, but it doesn't append a 5: it moves a pointer five characters into the literal, giving ": ". With a larger number it points outside the literal entirely, which is undefined behavior. Convert numbers with std::to_string(5) or, better, build the whole text with std::format("Score: {}", 5). Formatting is covered fully in Formatting with std::format and std::print.

+= is usually more efficient than s = s + x, because it appends in place instead of building a new string and copying it back. In a loop that builds a long string, prefer += (or append, which you'll meet in String Methods).

Length: size(), length() and empty()

s.size() and s.length() are two names for the same thing: the number of characters (strictly, the number of char elements) in the string. size() is the common choice because every standard container has it. s.empty() returns true for an empty string and reads better than s.size() == 0.

Two details matter in real programs:

  • size() returns std::size_t, an unsigned type. s.size() - 1 on an empty string doesn't give -1 but an enormous number. Check empty() first. See Integer Types.
  • size() counts bytes, not visible characters. Our editor saves your code as UTF-8, where letters like รฉ take two bytes and many emoji take four. So std::string("cafรฉ").size() is 5. Proper Unicode text processing needs a library (such as ICU); for ASCII text, bytes and characters are the same.

Reading and changing characters

Characters are numbered from 0. s[i] gives you the character at index i, and since std::string is mutable, you can assign to it too. s.front() and s.back() are the first and last character.

The difference between [] and at() is safety:

  • s[i] does no bounds checking. An index outside the string is undefined behavior: you might read garbage, crash, or corrupt memory silently.
  • s.at(i) checks the index and throws a std::out_of_range exception if it's invalid. You'll learn to handle exceptions in Exceptions; the example below catches one so you can see the message.
C++ Indexing with [], at(), front() and back()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Calling front() or back() on an empty string is undefined behavior too, just like s[0]. When the index comes from user input or a calculation you don't fully trust, use at() or check i < s.size() first.

Comparing strings

std::string supports all the comparison operators: ==, !=, <, <=, >, >= and C++20's <=>. Equality compares the characters, and the ordering is lexicographic: the strings are compared character by character, and the first difference decides, using each character's numeric code. If one string is a prefix of the other, the shorter one comes first.

C++ Comparing strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The results show why string comparison needs care:

  • It is case-sensitive: "Secret" and "secret" differ, and every uppercase ASCII letter sorts before every lowercase one, so "Zebra" < "apple". For case-insensitive comparison, convert both strings to one case first (shown in the next section).
  • It compares text, not numbers: "10" < "9" is true because '1' comes before '9'. Convert to numbers first if you need numeric order (Converting Between Strings and Numbers).

Looping over a string

Because a string is a sequence of characters, a range-based for loop visits each one. Loop by value (char c) to read characters, and by reference (char& c) to change them in place. An index loop is handy when you need the position too.

The character functions in <cctype>, such as std::toupper, std::isdigit and std::isspace, test and convert single characters. They expect values that fit in an unsigned char, so cast before calling them: a plain char may be negative for non-ASCII bytes, and passing a negative value is undefined behavior. Characters and Booleans explains why.

C++ Reading and changing every character

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Notice that changing shout left message untouched. std::string has value semantics: assignment and initialization copy the characters, so two string variables never share their text. That's convenient and safe, but copying a long string costs time and memory, which is why functions usually take strings as const std::string& (see Parameters) or as std::string_view (see std::string_view).

Reading strings from input

std::cin >> word reads a single word: it skips leading whitespace and stops at the next space, tab or newline. To read a whole line including spaces, use std::getline(std::cin, line). Both are covered in detail in Reading User Input, including the leftover-newline problem when you mix them. This example has its input preset in the Input box:

C++ Reading a word and a line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

std::ws discards whitespace, including the newline left behind by >>, before getline starts reading.

How std::string stores text. A std::string holds a pointer to its characters, a size and a capacity, and allocates more memory when it needs to grow. Most implementations also use the small string optimization: short strings (up to 15 characters with GCC's library) are stored inside the string object itself, with no heap allocation at all. That's one reason std::string is fast in practice. The characters are always followed by a hidden '\0', so c_str() can hand them to C functions, as you'll see in String Methods.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? std::string s = "cat"; s[0] = 'b'; std::println("{}", s);

    std::string is mutable. Assigning to s[0] replaces the first character in place.
  2. 2. Which line does not compile?

    Two string literals are arrays that decay to pointers, and pointers can't be added. Adjacent literals without + are joined at compile time, which is fine.
  3. 3. What happens with std::string s = "abc"; char c = s.at(5);?

    at() checks the index and throws std::out_of_range when it is invalid. s[5] would be undefined behavior instead.
  4. 4. Which is true for std::string("10") < std::string("9")?

    Strings compare lexicographically, character by character. The first characters '1' and '9' already decide it.
  5. 5. After std::string a = "hi"; std::string b = a; b += '!';, what is a?

    Initializing b from a copies the characters. The two strings are independent, so changing b doesn't affect a.

Summary

  • std::string (from <string>) owns a mutable, growable sequence of characters; a default-constructed string is empty, never garbage.
  • String literals are const char arrays, not std::string; auto s = "x" gives a pointer, while "x"s gives a std::string.
  • + and += concatenate; at least one operand of each + must be a std::string. Convert numbers with std::to_string or use std::format, and never write "text" + number.
  • size()/length() count bytes and return an unsigned std::size_t; empty() tests for an empty string.
  • s[i] is unchecked; s.at(i) throws std::out_of_range. Indexes start at 0.
  • Comparisons are lexicographic and case-sensitive, and compare text, not numeric values.
  • Loop with for (char c : s) to read and for (char& c : s) to modify; cast to unsigned char before <cctype> functions.
  • Strings are copied by value, so pass them to functions by const std::string& or std::string_view.

Next: String Methods, a tour of find, substr, replace, insert, erase and the C++23 contains.