01 / 21
s t r

std::string
Operations

Master C++ string manipulation: length, substr, find, and concatenation to build powerful text-processing programs.

C++

What is std::string?

In C++, std::string is a class from the <string> header that manages a dynamic sequence of characters. Unlike C-style character arrays, std::string automatically handles memory allocation and resizing.

#include <string> #include <iostream> int main() { std::string greeting = "Hello, World!"; std::cout << greeting << std::endl; return 0; }

Strings as Indexed Characters

A std::string stores characters at zero-based indices. Each character can be accessed using operator[] or the .at() method.

'H' 'e' 'l' 'l' 'o' ',' ' ' 'W' 'o' 'r' 'l' 'd' '!' 0 1 2 3 4 5 6 7 8 9 10 11 12 s[0] s[12]

Why std::string Over C-Strings?

C++ inherited C-style strings (char arrays), but std::string is safer, more flexible, and far easier to use for modern programming.

✓ Automatic Memory
No manual allocation or null-terminator management needed.
✓ Built-in Methods
Rich API: length, find, substr, replace, and more.
✓ Safe Comparison
Use == to compare content, not pointer addresses.

The Core Operations

Every C++ programmer must master these four essential string operations. They form the foundation of all text manipulation.

std::string .length() .substr() .find() + concat

.length() and .size()

Both .length() and .size() return the number of characters in the string. They are identical in behavior: .size() was added for STL container consistency.

std::string msg = "Hello!"; std::cout << msg.length(); // 6 std::cout << msg.size(); // 6 (same result)

Extracting with .substr()

.substr(pos, len) returns a new string starting at index pos with up to len characters. If len is omitted, it extracts through the end.

P r o g r a m m e 0 1 2 3 4 5 6 7 8 .substr(2, 3) = "ogr"
std::string s = "Programme"; s.substr(2, 3); // "ogr" (3 chars from index 2) s.substr(5); // "amme" (index 5 to end) s.substr(0, 2); // "Pr" (first 2 chars)

Searching with .find()

.find(target) searches for a substring or character and returns the index of the first occurrence. If not found, it returns std::string::npos.

std::string s = "Hello, World!"; size_t pos = s.find("World"); // pos == 7 size_t bad = s.find("xyz"); // bad == std::string::npos (not found) if (s.find("World") != std::string::npos) { std::cout << "Found it!"; }

Concatenation with + and +=

The + operator joins two strings into a new one. The += operator appends to an existing string in place, which is more efficient for building strings incrementally.

std::string first = "Hello"; std::string second = " World"; std::string result = first + second; // result == "Hello World" first += "!"; // first == "Hello!" // Append a single character: first.push_back('?'); // first == "Hello!?"
+ Operator
Creates a new string. Original strings unchanged.
+= Operator
Modifies the string in place. More efficient in loops.

operator[] vs .at()

Both access individual characters by index, but they differ in safety. Understanding when to use each is critical for robust code.

operator[] .at()
Bounds checking None Yes
Out-of-range Undefined behavior Throws std::out_of_range
Performance Faster Slight overhead
Best for Validated indices Untrusted input

How to Apply String Operations

Follow this checklist when working with strings in any C++ program:

1
Include the header: always start with #include <string>.
2
Declare with std::string: avoid raw char arrays for new code.
3
Check .length() before indexing: prevent out-of-bounds errors.
4
Use .find() + npos check: always verify before using the result.
5
Prefer += over + in loops: avoid creating unnecessary temporary strings.

Example 1: Extract a First Name

Given a full name like "Alice Johnson", extract just the first name using .find() and .substr().

std::string full = "Alice Johnson"; // Step 1: Find the space size_t space = full.find(' '); // space == 5 // Step 2: Extract from 0 to space std::string first = full.substr(0, space); // first == "Alice"

Example 2: File Extension Check

Determine if a filename ends with ".cpp" by using .length() and .substr().

std::string file = "main.cpp"; std::string ext = ".cpp"; if (file.length() >= ext.length()) { std::string ending = file.substr( file.length() - ext.length() ); // ending == ".cpp" if (ending == ext) { std::cout << "It's a C++ file!"; } }

Example 3: Build a Sentence

Concatenate words from a vector into a single sentence with spaces between them.

#include <vector> std::vector<std::string> words = { "C++", "strings", "are", "powerful" }; std::string sentence; for (size_t i = 0; i < words.size(); ++i) { if (i > 0) sentence += " "; sentence += words[i]; } // sentence == "C++ strings are powerful"

Common Mistakes with Strings

✕ Unchecked .find()
Using the return value of .find() without comparing to std::string::npos can produce garbage indices.
✕ Off-by-One in .substr()
Confusing pos (start index) with len (count): .substr(2, 3) gives 3 chars, not chars 2 through 3.
✕ Comparing C-strings with ==
Using == on C-strings (char*) compares pointers, not content. For std::string, == correctly compares the string's content.
✕ Forgetting #include
Some compilers implicitly include <string> via <iostream>, but this is not guaranteed. Always include it explicitly.

Quick Reference Table

Operation Syntax Returns
Length s.length() / s.size() Number of characters
Substring s.substr(pos, len) New string
Find s.find(target) Index or npos
Concatenate s1 + s2 / s1 += s2 Combined string
Access s[i] / s.at(i) Character (char)
Empty check s.empty() bool

Question 1 of 5

What does s.substr(3, 4) return when s = "Compiler"?

Question 2 of 5

What does s.find("xyz") return when s = "Hello"?

Question 3 of 5

Given std::string a = "Code"; std::string b = a + "!"; what is the value of a after this code runs?

Question 4 of 5

Which code correctly extracts the last name from "Jane Doe"?

Question 5 of 5

What is the key difference between s[10] and s.at(10) when the string has only 5 characters?