Module 4 · Pointers, Arrays, Strings and Structures — topic 3 of 4
Strings (std::string)
std::string manages text safely: construction, concatenation, comparison, searching, substrings, conversion to and from numbers, and string_view.
Learning objectives
- Create, compare and concatenate strings
- Search and extract with find and substr
- Convert between strings and numbers
Definition
std::string is a standard library class representing a mutable, dynamically sized sequence of characters that manages its own memory and supports value semantics.Introduction
C strings require you to manage buffers and terminators. std::string does that for you: it grows as needed, can be compared with ==, joined with + and copied with =.
Why it matters
Text processing — names, commands, file lines — appears in every project; std::string removes buffer overflows.
String manipulation questions (palindromes, reversal, counting) are interview staples.
Detailed explanation
Construction: std::string s = "hello";, std::string line(5, '-');. Length: s.size() (or length()).
Operators: + and += concatenate; ==, < compare lexicographically; s[i] accesses a character (unchecked), s.at(i) with a check.
s.find(t) returns the index of the first match or std::string::npos if absent; s.substr(pos, len) extracts a part; s.replace, s.erase, s.insert modify in place.
Numbers: std::to_string(42); std::stoi("42"), std::stod("3.5") (these throw std::invalid_argument on bad input).
std::string_view (C++17) is a lightweight, non-owning view of characters — ideal for read-only parameters, but it must not outlive the string it views.
Syntax
- Include
<string>. - Compare
findresults withstd::string::npos. c_str()gives aconst char*for C APIs.
Code examples
Building and comparing
apple & banana (14) 1 1
find and substr
asha.rao kenholt.in not gmail
More examples
Word processing
4 words, longest 'never' palindrome: true total: 42
Step-by-step explanation
std::istringstreamlets you read words from a string with>>.- The longest word is tracked by comparing sizes (ties keep the first).
is_palindromekeeps only letters and digits, lower-cased.std::equalcompares the first half with the reversed sequence.
Expected output
Running “Word processing” prints exactly:
Practical applications
- Parsers and command interpreters split strings into tokens.
- Web back ends build JSON and HTML as strings.
- Validation code searches for '@' and domains in emails.
Best practices
- Use std::string for owned text and string_view for read-only parameters.
- Check
nposafter every find. - Handle exceptions from stoi/stod when parsing user input.
Common mistakes
Comparing find with -1 or 0
Avoid
Prefer
find returns an unsigned position; not found is npos, and a match at index 0 is still found.
Dangling string_view
Avoid
Prefer
The temporary string is destroyed at the end of the statement, leaving the view pointing to freed memory.
Important notes
- Short strings are usually stored inside the object without heap allocation (small-string optimisation).
<cctype>functions needunsigned chararguments to avoid undefined behaviour with negative chars.
Key takeaways
- std::string supports +, ==, <, find, substr.
- Not found is
std::string::npos. - Convert with to_string and stoi/stod.
Try it yourself
- 1Count the vowels in a line read with getline.
- 2Replace every occurrence of a word in a sentence using find and replace in a loop.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
7 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- BeginnerWhat does `s.find("x")` return when "x" is not in s?
- BeginnerWhat is printed?