Lesson 10 — Data Structures

Strings

The std::string class stores and manipulates text of any length, handling memory management for you so you don't have to work with raw character arrays.

Creating and Combining Strings

Strings can be concatenated with +, compared with relational operators, and measured with .length(). Because std::string manages its own memory, you never need to worry about running out of space as text grows.

C++ — String basics
#include <string>

std::string first = "Nomvula";
std::string last = "Dlamini";
std::string fullName = first + " " + last;

std::cout << fullName << std::endl;
std::cout << "Length: " << fullName.length() << std::endl;
std::cout << "Uppercase first letter: " << fullName[0] << std::endl;

Common String Methods

The std::string class provides many useful methods for searching and extracting parts of text.

  • .substr(start, len) — extracts a portion of the string.
  • .find("text") — returns the index of the first match, or std::string::npos if not found.
  • .replace(pos, len, "new") — replaces part of a string.
  • .empty() — returns true if the string has zero length.

Common Mistakes

  • Comparing a std::string with == against a raw char* literal incorrectly, or mixing up C-style strings with std::string.
  • Forgetting that .find() returns std::string::npos (not -1) when nothing is found.
  • Off-by-one errors when using .substr() with the wrong starting index or length.
  • Modifying a string while iterating over its characters with an index that no longer matches after the change.

Professional Tip

Always check if (str.find("text") != std::string::npos) rather than comparing to -1npos is an unsigned value defined specifically to represent "not found".

Your Turn

Write a program that asks the user for a sentence, then prints how many characters it contains and whether it contains the word "the" (case-sensitive).

Mini Quiz

What does .find() return when the search text is not present in the string?