Explain it simply
Explain it simply
A std::string is a variable that holds text: a name, a message, a product code. Unlike a fixed-size box, it grows and shrinks as you add or remove characters, and it cleans up its own memory when it goes out of scope. Include <string>, write std::string name = "Sai";, and from then on you can join it with +, ask for its size, read single characters and search inside it.
Text in double quotes, such as "Sai", is not a std::string by itself. It is a string literal, a fixed array of characters inherited from C. Most of the time C++ converts it for you, but knowing the difference explains a few confusing compile errors you will meet in this lesson.
Problem → Why → Solution
The problem: a domain that is not a domain
A sign-up form stores e-mail addresses, and a report needs the domain part of each one. The code finds the @ sign and takes everything after it, and it works for every address in the test data. Then a user types aye.aye with no @ at all, and the report proudly lists aye.aye as a domain. A second line that reads character 20 of the same short string prints garbage, or nothing, depending on the machine.
#include <iostream>
#include <string>
int main() {
std::string email = "aye.aye"; // the user forgot the @
std::size_t at = email.find('@'); // not found
std::string domain = email.substr(at + 1); // what is at + 1?
std::cout << "Domain: " << domain << '\n'; // Domain: aye.aye
std::cout << email[20] << '\n'; // no bounds check
return 0;
}Why is it wrong without any error?
find() does not return -1 when it fails. It returns std::string::npos, the largest value a std::size_t can hold. Adding 1 to it wraps around to 0, because unsigned arithmetic wraps, so substr(0) quietly returns the whole string. And operator[] never checks the index: reading position 20 of a 7-character string is undefined behaviour, not an error message. Always compare find()'s result with std::string::npos, and use .at() when an index might be out of range.
Core concept: a string owns a row of bytes
std::string is a class from the standard library that owns a resizable buffer of char values, and each char is one byte. The string tracks how many bytes it holds, which .size() (or its twin .length()) returns as a std::size_t, an unsigned type. Copying a string with = or passing it by value creates a completely independent copy, so changing one never affects the other. Two strings are compared by content with ==, != and <, which compare character codes from left to right.
A string literal such as "Sai" has the type const char[4]: three letters plus a hidden '\0' terminator. The + operator only joins text when at least one side is a std::string, so firstName + " " works while "Hello, " + "world" is a compile error, because C++ would be trying to add two arrays. Building left to right from a std::string, or writing std::string("Hello, ") + "world", fixes it.
Positions start at 0. s[i] reads a character without any check, so an index past the end is undefined behaviour, while s.at(i) checks and throws std::out_of_range instead. s.find(text) returns the position of the first match, or std::string::npos when there is none, and s.substr(pos, count) copies a piece, where count defaults to "until the end". C++20 adds s.starts_with() and s.ends_with() for the common prefix and suffix checks.
Finally, size counts bytes, not letters. Source files and terminals today almost always use UTF-8, where an English letter takes one byte but each Myanmar code point takes three. std::string("မြန်မာ").size() is 18: six code points times three bytes, even though a reader sees two syllables. Indexing such a string with [] returns single bytes that are only fragments of a character.
| Expression (s = "Sai Tun") | Result | Note |
|---|---|---|
| s.size() | 7 | byte count, std::size_t |
| s[0] | 'S' | no bounds check |
| s.at(10) | throws | std::out_of_range |
| s.find(' ') | 3 | position of the first match |
| s.find('@') | std::string::npos | not found |
| s.substr(4) | "Tun" | copy from index 4 to the end |
- A string owns bytes, numbered from 0
- + joins only if one side is a string
- find gives a position or npos
- substr copies the piece you asked for
Every number a string gives you (size, position, npos) is an unsigned std::size_t, so check it before doing arithmetic with it.
General pattern
#include <string>
std::string text = "literal"; // owns a copy of the characters
std::string joined = text + " more"; // one side must be a std::string
std::size_t n = text.size(); // bytes, as an unsigned size_t
char first = text[0]; // unchecked; text.at(0) checks
std::size_t pos = text.find("lit"); // std::string::npos if missing
std::string piece = text.substr(pos, count);Create a std::string from a literal and join with +, and size() gives the byte count. [] reads without checking while at() checks. Compare find()'s result with std::string::npos before passing it to substr().
Example: join, measure and search a name
This program joins two name parts and then inspects the result: its size, its first character, where the space is, the family name, and a search for an @ that is not there. The last two lines measure a Myanmar city name to show that bytes and letters are not the same thing.
#include <iostream>
#include <string>
int main() {
std::string firstName = "Sai";
std::string lastName = "Tun";
std::string fullName = firstName + " " + lastName;
std::cout << "Full name: " << fullName << '\n';
std::cout << "Length: " << fullName.size() << '\n';
std::cout << "First letter: " << fullName[0] << '\n';
std::size_t space = fullName.find(' ');
std::cout << "Space at index: " << space << '\n';
std::cout << "Family name: " << fullName.substr(space + 1) << '\n';
std::cout << std::boolalpha
<< "Has @? " << (fullName.find('@') != std::string::npos) << '\n';
fullName += " (student)";
std::cout << "Updated: " << fullName << '\n';
std::string city = "မန္တလေး";
std::cout << "Bytes in city name: " << city.size() << '\n';
return 0;
}Code breakdown
- Joining
std::string fullName = firstName + " " + lastName;+ works here because the expression is evaluated left to right and firstName is already a std::string: firstName + " " produces a new std::string, which is then joined with lastName.
- Size in bytes
fullName.size()Seven bytes: three letters, one space, three letters. For plain English text bytes and letters match, so 7 is also the number of characters you see.
- Index 0
fullName[0]Positions start at 0, so [0] is S. [] does no bounds check; fullName.at(0) would give the same S but throw std::out_of_range for an index of 7 or more.
- Find and slice
fullName.substr(space + 1)find(' ') returns 3, the index of the space, so substr(4) copies from index 4 to the end: Tun. This is safe only because we know a space exists; the next line shows how to ask first.
- Not found
(fullName.find('@') != std::string::npos)There is no @, so find returns std::string::npos and the comparison is false. Comparing with npos is the correct test for "was it found?".
- Appending
fullName += " (student)";+= appends to the existing string in place, and the string grows its buffer as needed.
- UTF-8 bytes
city.size()မန္တလေး has seven code points, each stored as three UTF-8 bytes, so size() reports 21, not the number of letters a reader would count.
Full name: Sai Tun
Length: 7
First letter: S
Space at index: 3
Family name: Tun
Has @? false
Updated: Sai Tun (student)
Bytes in city name: 21Searching safely with find and npos
Whenever text comes from a user or a file, assume the thing you are looking for might be missing. Store find()'s result, compare it with std::string::npos, and only then slice. The if statement used below is covered properly in the next lesson; here it simply skips the slicing when nothing was found.
#include <iostream>
#include <string>
int main() {
std::string email = "thida@example.com";
std::size_t at = email.find('@');
if (at != std::string::npos) {
std::cout << "User: " << email.substr(0, at) << '\n';
std::cout << "Domain: " << email.substr(at + 1) << '\n';
}
std::string typo = "aye.aye";
if (typo.find('@') == std::string::npos) {
std::cout << "No @ in " << typo << '\n';
}
return 0;
}std::string_view: a window, not a copy
Passing a std::string by value copies all of its bytes. Where code only needs to read text, C++17's std::string_view is cheaper: it is just a pointer to someone else's characters plus a length, and it accepts std::string objects and string literals alike. Its member functions mirror the read-only half of std::string: size(), find(), substr(), starts_with() and ends_with(). substr() on a string_view copies nothing and simply returns a narrower view.
#include <iostream>
#include <string>
#include <string_view>
int main() {
std::string title = "Learn C++ step by step";
std::string_view view = title; // no copy: points into title
std::string_view firstWord = view.substr(0, 5);
std::cout << firstWord << '\n';
std::cout << view.size() << " bytes viewed\n";
std::cout << std::boolalpha << view.starts_with("Learn") << '\n';
return 0;
}A view must not outlive its text
A std::string_view never owns characters, so it must not outlive the string it points into. std::string_view bad = std::string("temp") + "orary"; compiles under g++ -Wall -Wextra without a single warning, yet the temporary string is destroyed at the end of that line and bad is left pointing at freed memory. Reading it is undefined behaviour. Keep views for parameters and short local use, and store a std::string whenever the text must live on.
In real projects
Where this shows up in real projects
Almost every program handles text at its edges. Web servers split request paths such as /users/42 on the slash, command-line tools look for flags that starts_with("--"), log analysers find() a keyword on each line, and configuration loaders cut key=value lines in two around the =. All of these are find() plus substr() with a careful npos check, exactly the pattern in this lesson.
Bilingual sites like this one are where the difference between bytes and letters bites. A database column limited to 50 characters, an SMS gateway that counts characters, or a UI that shortens a title with substr(0, 20) can each cut a Myanmar word in the middle of a three-byte sequence and display broken symbols. Real projects either measure and cut text with a Unicode-aware library such as ICU, or keep the text whole and let the UI layer handle truncation.
Common mistakes
Common mistakes
1. Adding two string literals
"Hello, " + "world" fails with error: invalid operands of types 'const char [8]' and 'const char [6]' to binary 'operator+'. Neither side is a std::string, so there is no + to call. Start from a std::string (std::string("Hello, ") + "world") or simply write one literal, "Hello, world".
2. Adding a char to a literal
email[0] + "***" looks like joining, but a char plus a const char* is pointer arithmetic: the char's code moves the pointer forward, and the result points somewhere past the end of the literal. Wrap the char first: std::string(1, email[0]) + "***".
3. Testing find() as if it returned a bool
if (s.find("x")) is true when the match sits at any position other than 0, and also when nothing was found, because npos is non-zero. A match at the very start of the string, meanwhile, counts as false. The only correct test is s.find("x") != std::string::npos.
4. Treating size() as a letter count
For Myanmar or emoji text, size() is the number of UTF-8 bytes. Use it for memory and protocol limits, but not to promise users a character count or to decide where substr() cuts the text.
Best practices
Best practices
- Include <string> yourself instead of relying on <iostream> to bring it in.
- Store find() results in a std::size_t and compare them with std::string::npos before slicing.
- Use .at() while learning or whenever an index comes from input, and switch to [] only where the bounds are already proven.
- Take read-only text parameters as std::string_view or const std::string&, and return std::string when the caller must own the result.
Mini challenge
Mini challenge: file name inspector
A document manager needs to show information about uploaded files. Write a program that takes a file name apart with the string tools from this lesson.
- Find the last dot in file with rfind('.') and print the base name and extension with substr
- Print whether file ends with ".pdf" using ends_with (C++20) as true/false
- Build a backup name that replaces the extension with "bak"
- Print whether "README" contains a dot by comparing rfind's result with std::string::npos
#include <iostream>
#include <string>
int main() {
std::string file = "report.final.pdf";
std::string noExtension = "README";
// TODO: find the LAST dot in file (look up rfind)
// TODO: print the base name and the extension with substr
// TODO: print whether file ends with ".pdf" (C++20 ends_with)
// TODO: build and print a backup name that ends in ".bak"
// TODO: print whether noExtension contains a dot (compare with npos)
return 0;
}Expected: The output should be: Base name: report.final Extension: pdf Is PDF? true Backup name: report.final.bak README has a dot? false
Show hint
rfind() works like find() but searches from the end, so it finds the dot before pdf rather than the one after report. substr(0, dot) copies everything before the dot, and substr(dot + 1) everything after it.
Show solution
#include <iostream>
#include <string>
int main() {
std::string file = "report.final.pdf";
std::string noExtension = "README";
std::size_t dot = file.rfind('.');
std::string base = file.substr(0, dot);
std::string extension = file.substr(dot + 1);
std::cout << "Base name: " << base << '\n';
std::cout << "Extension: " << extension << '\n';
std::cout << std::boolalpha;
std::cout << "Is PDF? " << file.ends_with(".pdf") << '\n';
std::string backup = base + ".bak";
std::cout << "Backup name: " << backup << '\n';
bool hasDot = noExtension.rfind('.') != std::string::npos;
std::cout << noExtension << " has a dot? " << hasDot << '\n';
return 0;
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- std::string owns a growable buffer of bytes; copies are independent and == compares content.
- String literals are const char arrays, so + needs at least one std::string operand.
- [] is unchecked, .at() throws std::out_of_range, and find() returns std::string::npos when nothing matches.
- size() counts UTF-8 bytes, so Myanmar text reports about three times its code point count.
- std::string_view is a cheap read-only view that must never outlive the text it points into.
The Current ISO C++ Standard (C++23) — Standard C++ Foundation