01 / 24

std::string
A Container of Characters

Master the C++ string class: how it stores, manipulates, and accesses sequences of characters dynamically.

C++

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.

#include <string>

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.

H e l l o size() = 5 extra capacity [0] [1] [2] [3] [4] std::string "Hello"

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[] Problems
Fixed size, manual memory, no bounds checking, buffer overflows
std::string Fixes
Dynamic size, automatic memory, safe access via .at(), no overflows

Ways to Create a String

1
Default: std::string s; creates an empty string with size 0.
2
From literal: std::string s = "Hello"; copies the literal into managed memory.
3
Fill constructor: std::string s(5, 'x'); creates "xxxxx".
4
Copy: std::string s2 = s1; creates an independent copy of s1.
5
Substring: std::string s(other, 2, 4); extracts 4 characters starting at index 2.

The Core Operations

std::string Access [ ] .at() Size / Capacity Modify / Append Search / Find Compare / ==

Accessing Characters

s[i]
Access by index. Fast but no bounds checking: undefined behavior if out of range.
s.at(i)
Access by index with bounds checking: throws std::out_of_range if invalid.
s.front() / s.back()
Returns the first or last character directly. Must not call on empty string.
std::string s = "Code";
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

1
Append: s += "more"; or s.append("more"); adds text to the end.
2
Insert: s.insert(3, "XY"); inserts "XY" starting at position 3.
3
Erase: s.erase(2, 4); removes 4 characters starting at index 2.
4
Replace: s.replace(0, 3, "Hi"); replaces 3 chars at position 0 with "Hi".
5
Clear: s.clear(); removes all characters; size becomes 0.

Size vs Capacity

size() = 5 capacity() = 15 unused space String Memory Layout
.size()
Number of characters currently stored. Same as .length().
.capacity()
Total allocated space. Grows automatically when you add characters beyond current capacity.
.empty()
Returns true if size() == 0. Cleaner than checking size manually.

Searching Within a String

std::string s = "Hello, World!";

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()
First occurrence, left to right
.rfind()
Last occurrence, right to left

Substrings & Concatenation

std::string full = "Programming";

// 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

1
Include the header: #include <string> at the top of your file.
2
Declare and initialize: use std::string name = "value"; or the fill/copy constructors.
3
Access characters: use .at(i) for safety or [i] for speed. Iterate with a range-based for loop.
4
Modify as needed: append with +=, insert, erase, or replace characters.
5
Search and extract: use .find() to locate substrings, .substr() to extract them.

Example: Counting Vowels

#include <string>
#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 <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 s = "I love cats and cats love me";
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

✕ Out-of-Bounds Access
Using s[s.size()] reads past the end. The last valid index is s.size() - 1.
✕ Confusing size_t with int
.find() returns size_t (unsigned). Comparing against -1 instead of npos can cause subtle bugs.
✕ Forgetting #include
String literals work without the header, but std::string operations require #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.

std::string s = "hello";

// 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"?

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?

Question 4 of 5

What is the output of this code?
std::string s = "ABCDEF"; std::cout << s.substr(2, 3);

Question 5 of 5

Which loop correctly converts every character to uppercase in place?