The Analogy: A Bead Bracelet That Grows
A std::string is a bracelet of character beads. You can count the beads, look at the fifth one, snip out a section, join two bracelets together, or add beads to the end — and the bracelet stretches to fit. You never decide in advance how long it will be.
Older C++ (and all of C) used a different thing: a fixed-length tray of characters ending in a special marker bead, '\0'. If you tried to add more beads than the tray held, you scribbled over whatever sat next to it in memory. That is the origin of a very large share of security vulnerabilities in the world.
std::string exists so you never have to manage the tray yourself. Use it for everything.
Syntax or Core Structure
#include <iostream>
#include <string>
int main() {
std::string name{"Ada Lovelace"};
std::string empty; // valid, length 0
std::string repeated(5, '*'); // "*****"
// Size
std::cout << name.length() << "\n"; // 12 (size() is identical)
std::cout << name.empty() << "\n"; // 0 (false)
// Individual characters -- zero indexed
std::cout << name[0] << "\n"; // 'A'
std::cout << name.front() << "\n"; // 'A'
std::cout << name.back() << "\n"; // 'e'
std::cout << name.at(100) << "\n"; // THROWS -- at() checks, [] does not
// Joining
std::string greeting = "Hello, " + name + "!";
greeting += " Welcome.";
// Searching and slicing
std::cout << name.find("Love") << "\n"; // 4
std::cout << name.find("zzz") << "\n"; // std::string::npos (huge number)
std::cout << name.substr(0, 3) << "\n"; // "Ada" (start, length)
std::cout << name.substr(4) << "\n"; // "Lovelace"
// Editing
name.push_back('!'); // append one char
name.insert(0, "Dear "); // "Dear Ada Lovelace!"
name.replace(0, 4, "Ms."); // swap 4 chars at position 0
name.clear(); // now empty
return 0;
}
length() and size() are the same function with two names — size() matches every other container, length() reads better for text. Both are fine.
Technical Depth: npos, Copies and Conversions
find does not return -1
std::string text{"config.json"};
std::size_t dot = text.find('.');
if (dot != std::string::npos) {
std::cout << text.substr(dot + 1) << "\n"; // "json"
}
// The trap:
if (text.find("xml") > 0) { } // npos is a HUGE unsigned number, so this is TRUE
// even though "xml" was not found
find returns std::string::npos on failure — the largest possible size_t, not -1. Because it is unsigned, comparing it with > or >= 0 gives nonsense. Always compare against npos explicitly.
[] versus at()
std::string s{"abc"};
char a = s[10]; // undefined behaviour -- may return garbage, may crash later
char b = s.at(10); // throws std::out_of_range -- you can catch it
[] is fast and unchecked; at() is bounds-checked and throws. Use at() when the index came from outside your control, [] inside a loop you have already bounded.
Strings copy by value
void printBad(std::string s); // COPIES the whole string every call
void printGood(const std::string& s); // borrows it -- no copy
void printBest(std::string_view s); // C++17: borrows any text at all
std::string a{"hello"};
std::string b = a; // b is an independent copy
b[0] = 'H'; // a is still "hello"
Unlike Java or Python, assigning a string duplicates its contents. That is usually what you want, but passing by value into a function is wasted work. Take const std::string& for read-only parameters — this is the single most impactful string habit in C++. std::string_view goes further: it works for std::string, string literals and character arrays without copying any of them, at the cost of not owning the data (never return a view of a local string).
Comparing and converting
std::string x{"apple"}, y{"banana"};
bool same = (x == y); // works exactly as you would hope -- compares content
bool before = (x < y); // true -- lexicographic, so "apple" sorts first
// note: uppercase letters sort BEFORE lowercase
// Number <-> string
std::string n = std::to_string(42); // "42"
int back = std::stoi("42"); // 42
double d = std::stod("3.14"); // 3.14
int bad = std::stoi("banana"); // THROWS std::invalid_argument
// C-string interop (for old APIs)
const char* raw = x.c_str(); // null-terminated pointer, do not free it
Note that == compares content, which surprises people arriving from Java where it compares identity. And std::stoi throws rather than returning zero, so wrap it in try/catch when parsing user input.
Iterating
std::string word{"Hello"};
for (char c : word) { std::cout << c << " "; } // read-only copy of each char
for (char& c : word) { c = std::toupper(c); } // reference -- modifies in place
for (std::size_t i = 0; i < word.size(); ++i) { } // when you need the index
The char& form is how you edit in place; without the ampersand you are changing a copy and the original is untouched.
Real World Example: Parsing an Email Address
#include <iostream>
#include <string>
#include <cctype>
// Borrow the string -- no copy
bool looksLikeEmail(const std::string& input) {
const std::size_t at = input.find('@');
if (at == std::string::npos) return false; // no @ at all
if (at == 0) return false; // nothing before it
if (input.find('@', at + 1) != std::string::npos) return false; // a second @
const std::string domain = input.substr(at + 1);
const std::size_t dot = domain.find('.');
if (dot == std::string::npos) return false; // domain has no dot
if (dot == 0) return false; // ".com" with no name
if (dot + 1 >= domain.size()) return false; // trailing dot
return true;
}
std::string normalise(std::string input) { // by value: we want our own copy
for (char& c : input) {
c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
}
// Trim trailing spaces
while (!input.empty() && input.back() == ' ') {
input.pop_back();
}
return input;
}
int main() {
const std::string raw{" Ada.Lovelace@Example.COM "};
std::string cleaned = normalise(raw);
cleaned.erase(0, cleaned.find_first_not_of(' ')); // trim leading spaces
std::cout << "Cleaned: [" << cleaned << "]\n";
std::cout << "Valid: " << std::boolalpha << looksLikeEmail(cleaned) << "\n";
std::cout << "User: " << cleaned.substr(0, cleaned.find('@')) << "\n";
std::cout << "Domain: " << cleaned.substr(cleaned.find('@') + 1) << "\n";
return 0;
}
The two parameter styles are deliberate. looksLikeEmail only reads, so it takes const std::string& and copies nothing. normalise needs to modify, so it takes the string by value — it gets its own copy to mutate and return, which is cleaner than taking a reference and editing the caller's data. find_first_not_of plus erase is the standard trim idiom. And every find result is checked against npos before use.
Common Mistakes
- Comparing
findagainst-1or> 0. It returns unsignednpos; compare withstd::string::npos. - Passing
std::stringby value to read-only functions. Copies the entire text on every call. "Hello" + " world"does not compile — two string literals cannot be added. Wrap one:std::string{"Hello"} + " world".- Using
[]on an index you did not verify. Undefined behaviour;at()at least throws. - Forgetting
#include <string>. It often works by accident via another header, then breaks on a different compiler. - Iterating with
for (char c : s)and assigning toc. You are editing a copy. Usechar&. - Returning a
std::string_viewof a local string. The string dies, the view dangles. - Assuming one
charis one visible character. It is one byte; accented letters and emoji take several in UTF-8, so.length()is a byte count.
Best Practices
- Use
std::string, never rawchar[], unless a C API forces your hand. - Take
const std::string&for read-only parameters,std::stringby value when you need your own mutable copy. - Always check
findagainstnposbefore using the result. - Reach for
std::string_view(C++17) for read-only parameters that might receive literals — but never store or return one that outlives its source. - Wrap
std::stoiintry/catchwhen the text came from a user or a file. - Use
.empty()rather than.length() == 0. It states the intent and is never slower.
Practice Exercises
- Palindrome check: Write
bool isPalindrome(const std::string& s)that ignores case and non-letter characters, so"A man, a plan, a canal: Panama"returns true. - Word counter: Read a full line with
std::getlineand report the number of words, the longest word, and the average word length. Handle multiple consecutive spaces correctly. - CSV splitter: Given
"name,age,city", usefindandsubstrin a loop to print each field on its own line — without using any library beyond<string>.