Beginner⏱️ 9 min📘 Topic 13 of 32

🔤 Strings in C++ — std::string, Methods and Manipulation

Master std::string in C++ — concatenation, substring, find, replace, length and comparison. Differences from C-strings, common operations and interview-ready examples.

Modern C++ uses std::string from <string> — a dynamic, safe text container. Older C code uses char[] (C-strings) which are harder to work with.

📜 Basics

#include <string>
std::string name = "Sam";
name += " Smith";          // concat
std::cout << name.size();  // 9
std::cout << name[0];       // 'S'

🔧 Common methods

  • .length() / .size() — number of characters
  • .empty() — is it ""?
  • .substr(start, count) — extract a piece
  • .find("abc") — index or std::string::npos
  • .replace(start, count, "new")
  • .append("...") — like +=

🔍 Searching

std::string s = "hello world";
size_t pos = s.find("world");
if (pos != std::string::npos) {
  std::cout << "found at " << pos;
}

💡 Comparison

Use == with std::string. C-strings need strcmp.

💻 Code Examples

Concatenate, substring, replace

std::string s = "Hello, World!";
std::cout << s.substr(7, 5) << '\n';        // World
s.replace(7, 5, "C++");
std::cout << s;                              // Hello, C++!
Output:
World
Hello, C++!

Reverse a string

#include <algorithm>
std::string s = "abcdef";
std::reverse(s.begin(), s.end());
std::cout << s;
Output:
fedcba

Count occurrences of a character

std::string s = "banana";
int count = 0;
for (char c : s) if (c == 'a') count++;
std::cout << count;
Output:
3

⚠️ Common Mistakes

  • Forgetting `#include <string>` — std::string is not in <iostream>.
  • Comparing C-strings with `==` — that compares POINTERS, not contents. Use strcmp or convert to std::string.
  • Using `find()` and checking `if (pos)` — that's true even for pos==1. Check `!= std::string::npos`.
  • Out-of-bounds with `[]` (no check) vs `at()` (throws) — pick based on safety vs speed needs.

🎯 Interview Questions

Real questions asked at top product and service-based companies.

Q1.What's the difference between std::string and a C-string?Beginner
std::string is a class — owns its memory, knows its length, has methods. A C-string is just a `char[]` ending in `'\0'` — manual memory, no length stored, function-based operations (strcmp, strcpy). Prefer std::string in modern C++.
Q2.What does std::string::npos mean?Beginner
A special value (typically -1 cast to size_t, so the largest possible size_t) returned by `find()` when the substring isn't found. Always check `pos != std::string::npos`.
Q3.How do you iterate a string character by character?Intermediate
Range-based for: `for (char c : s) { ... }`. Or indexed: `for (size_t i = 0; i < s.size(); i++)`. For modification by reference: `for (char& c : s)`.
Q4.Are std::strings null-terminated?Intermediate
Internally, yes — `s.c_str()` returns a null-terminated C-string. But the size is also stored separately, so std::string is faster and safer than relying on null termination.
Q5.What is std::string_view and when would you use it?Advanced
A non-owning, read-only view of a string (C++17). Doesn't copy data. Perfect for function parameters that only READ a string without taking ownership. Faster than const std::string& for literal arguments.

🧠 Quick Summary

  • std::string — modern, dynamic, safe text container.
  • .size(), .empty(), .substr(), .find(), .replace().
  • Compare with ==, append with +=, iterate with range-for.
  • Use std::string::npos to check find() failure.
  • Prefer std::string over char arrays in modern code.