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.
#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, orstd::string::nposif 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::stringwith==against a rawchar*literal incorrectly, or mixing up C-style strings withstd::string. - Forgetting that
.find()returnsstd::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 -1 — npos 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?
std::string::npos is a special constant representing "no position found", and comparing against it is the correct way to check for a failed search.