Module 10: StringsBeginner45 min read
C-Style Strings vs std::string & Essential String Methods
Compare null-terminated char arrays (<cstring>) with modern std::string, and master substr(), find(), replace(), insert(), erase(), and conversions.
Key Takeaways & Core Concepts
- C-Style Strings: Null-terminated
chararrays ('\0'). Functions in<cstring>(strlen,strcpy,strncpy,strcat,strcmp) require manual buffer management and risk buffer overflows. - `std::string` (`<string>`): Dynamic, RAII-managed string class supporting
+,==,.length(),.substr(),.find(),.replace(),.insert(),.erase(), andstd::to_string(). - Mistake: Comparing
find()with>= 0(sincefind()returnssize_t, an unsigned type!). Always compare withstd::string::npos. - Best Practice: Pass read-only strings as
const std::string&orstd::string_view(C++17) to avoid copies.
1. C-Style Strings vs. `std::string`
- C-Style Strings: Null-terminated
chararrays ('\0'). Functions in<cstring>(strlen,strcpy,strncpy,strcat,strcmp) require manual buffer management and risk buffer overflows. - `std::string` (`<string>`): Dynamic, RAII-managed string class supporting
+,==,.length(),.substr(),.find(),.replace(),.insert(),.erase(), andstd::to_string().
1. Palindrome Check & std::string Methods
1#include <iostream>
2#include <string>
3#include <algorithm>
4
5int main() {
6 std::string s = "CodeZov C++";
7 auto pos = s.find("C++");
8 if (pos != std::string::npos) s.replace(pos, 3, "2026");
9 std::cout << "Updated: " << s << "\n";
10
11 std::string word = "madam";
12 std::string rev = word;
13 std::reverse(rev.begin(), rev.end());
14 std::cout << word << " palindrome? " << (word == rev ? "Yes" : "No") << "\n";
15 return 0;
16}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
16 lines
Note: Checks `find()` against `std::string::npos` and reverses a string with `std::reverse`.
2. Internal Working: Small String Optimization (SSO)
Modern C++ standard libraries embed a small inline buffer (~15–22 bytes) inside std::string. Short strings are stored directly on the stack with zero heap allocation, while longer strings dynamically allocate on the heap.
3. Common Mistakes & Best Practices
- Mistake: Comparing
find()with>= 0(sincefind()returnssize_t, an unsigned type!). Always compare withstd::string::npos. - Best Practice: Pass read-only strings as
const std::string&orstd::string_view(C++17) to avoid copies.
Practice & AssessmentC++ Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)