LearnForFree
C++ For Beginners
Lesson

Strings (std::string) & Text Manipulation

In older C code, text was stored as arrays of characters ending with a null terminator ('\0'), which required manual memory management. Modern C++ provides std::string (via #include <string>), a safe, dynamic object packed with built-in methods for text processing. Key std::string Capabilities • Reading Full Lines (std::getline): Remember that std::cin >> text stops at spaces. To read an entire sentence containing spaces, use std::getline(std::cin, text);. • Concatenation (+ or +=): Easily join strings together (std::string full = first + " " + last;). • Length (.length() or .size()): Returns the total number of characters in the string. • Accessing Characters: Use str[i] or str.at(i) just like a vector. • Substrings (.substr(start_index, length)): Extracts a smaller piece of text from a string. • Searching (.find(query)): Returns the starting index of the first occurrence of query, or returns std::string::npos if not found. • Modifying (.replace(), .erase(), .insert()): Allows editing text directly in place.
#include <iostream> #include <string> int main() { std::string firstName = "Ada"; std::string lastName = "Lovelace"; // 1. Concatenation std::string fullName = firstName + " " + lastName; std::cout << "Full Name: " << fullName << "\n"; std::cout << "Character count: " << fullName.length() << "\n"; // 2. Extracting a Substring (starts at index 4, takes 4 characters) std::string part = fullName.substr(4, 4); std::cout << "Substring: " << part << "\n"; // Outputs "Love" // 3. Searching inside a string size_t pos = fullName.find("Lovelace"); if (pos != std::string::npos) { std::cout << "'Lovelace' found at index: " << pos << "\n"; } // 4. Modifying characters fullName[0] = 'E'; // Changes "Ada" to "Eda" std::cout << "Modified Name: " << fullName << "\n"; return 0; }

Watch companion video on YouTube

Sign in to save your progress