std::string
A Container of Characters
Master the C++ string class: how it stores, manipulates, and accesses sequences of characters dynamically.
What Is std::string?
A std::string is a C++ Standard Library class that manages a dynamic sequence of characters. Unlike a raw C-style character array, it automatically handles memory allocation, resizing, and cleanup.
std::string greeting = "Hello, World!";
How It Stores Characters
Internally, std::string keeps a contiguous block of memory on the heap. Each character occupies one byte, and the string tracks its current size and allocated capacity.
Why Not C-Style Strings?
C++ inherited null-terminated character arrays from C. They work, but they put the burden of memory management and safety entirely on the programmer. std::string solves these problems.
char[] Problemsstd::string Fixes.at(), no overflowsWays to Create a String
std::string s; creates an empty string with size 0.std::string s = "Hello"; copies the literal into managed memory.std::string s(5, 'x'); creates "xxxxx".std::string s2 = s1; creates an independent copy of s1.std::string s(other, 2, 4); extracts 4 characters starting at index 2.The Core Operations
Accessing Characters
s[i]s.at(i)std::out_of_range if invalid.s.front() / s.back()char c1 = s[0]; // 'C'
char c2 = s.at(2); // 'd'
char c3 = s.back(); // 'e'
s[i] vs s.at(i)
s[i] |
s.at(i) |
|
|---|---|---|
| Bounds Check | No | Yes |
| Out of Range | Undefined behavior | Throws exception |
| Speed | Slightly faster | Small overhead |
| Best For | Performance-critical loops | General use, debugging |
Modifying a String
s += "more"; or s.append("more"); adds text to the end.s.insert(3, "XY"); inserts "XY" starting at position 3.s.erase(2, 4); removes 4 characters starting at index 2.s.replace(0, 3, "Hi"); replaces 3 chars at position 0 with "Hi".s.clear(); removes all characters; size becomes 0.Size vs Capacity
.size().length()..capacity().empty()size() == 0. Cleaner than checking size manually.Searching Within a String
size_t pos = s.find("World"); // pos == 7
size_t bad = s.find("xyz"); // bad == std::string::npos
if (pos != std::string::npos) {
std::cout << "Found at index " << pos;
}
.find().rfind()Substrings & Concatenation
// Extract substring: .substr(start, length)
std::string part = full.substr(0, 7); // "Program"
// Concatenation with +
std::string result = part + "s rock!";
// result == "Programs rock!"
Step-by-Step: Using std::string
#include <string> at the top of your file.std::string name = "value"; or the fill/copy constructors..at(i) for safety or [i] for speed. Iterate with a range-based for loop.+=, insert, erase, or replace characters..find() to locate substrings, .substr() to extract them.Example: Counting Vowels
#include <iostream>
int main() {
std::string text = "Hello World";
int count = 0;
for (char c : text) {
if (c == 'a' || c == 'e' || c == 'i'
|| c == 'o' || c == 'u') {
count++;
}
}
std::cout << count; // 3
}
Example: Reversing a String
#include <algorithm>
#include <iostream>
int main() {
// Method 1: std::reverse (in-place)
std::string s1 = "abcde";
std::reverse(s1.begin(), s1.end());
// s1 is now "edcba"
// Method 2: construct reversed copy
std::string s2 = "abcde";
std::string rev(s2.rbegin(), s2.rend());
// rev is "edcba", s2 is unchanged
}
Example: Find and Replace
std::string target = "cats";
std::string replacement = "dogs";
size_t pos = s.find(target);
while (pos != std::string::npos) {
s.replace(pos, target.size(), replacement);
pos = s.find(target, pos + replacement.size());
}
// s == "I love dogs and dogs love me"
Common Mistakes
s[s.size()] reads past the end. The last valid index is s.size() - 1..find() returns size_t (unsigned). Comparing against -1 instead of npos can cause subtle bugs.#include <string>.Method Quick Reference
| Method | Purpose | Returns |
|---|---|---|
.size() / .length() |
Character count | size_t |
.empty() |
Is it empty? | bool |
.at(i) |
Safe character access | char& |
.find(str) |
Search for substring | size_t / npos |
.substr(pos, len) |
Extract substring | string |
.append(str) / += |
Add to end | string& |
.erase(pos, len) |
Remove characters | string& |
.replace(pos, len, str) |
Replace characters | string& |
.c_str() |
Get C-style char* | const char* |
String as a Container
std::string behaves like a std::vector<char>. It supports iterators, range-based for loops, and works with <algorithm> functions.
// Range-based for: read each character
for (char c : s) { /* ... */ }
// Range-based for: modify in place
for (char& c : s) { c = toupper(c); }
// s == "HELLO"
// Sort alphabetically
std::sort(s.begin(), s.end());
// s == "EHLLO"
Question 1 of 5
What does s.at(0) return when s = "Code"?
.at(0) returns the character at index 0, which is 'C'. std::string uses zero-based indexing, just like arrays.Question 2 of 5
What is the value of s.size() after executing:std::string s = "Hi"; s += "!!";
Question 3 of 5
What does .find() return when the substring is not found?
std::string::npos is a special constant (the maximum value of size_t) indicating "not found." Never compare against -1 directly, as size_t is unsigned.Question 4 of 5
What is the output of this code?std::string s = "ABCDEF"; std::cout << s.substr(2, 3);
.substr(2, 3) starts at index 2 (which is 'C') and takes 3 characters: "CDE". Remember: the first argument is position, the second is length.Question 5 of 5
Which loop correctly converts every character to uppercase in place?
char& (a reference) to modify the original character. Option A and D copy each character, so changes are lost. Option B calls toupper but discards the return value.