Topic 23 of 83
Strings
Overview
C-style strings are raw arrays of characters ending with a null terminator (\0). C++ introduced std::string, an object-oriented, dynamic, and infinitely safer way to handle text.
Syntax
cpp
// C-Style String
char c_str[] = "Hello"; // Size is 6 ('H', 'e', 'l', 'l', 'o', '\0')
// Modern C++ std::string
#include <string>
std::string cpp_str = "Hello";
cpp_str += " World!"; // Easy concatenationCommon Pitfalls
- Forgetting the null terminator
\0when manually building a C-style char array, causing buffer over-reads. - Trying to assign one C-string to another using
=(you must usestrcpy).
Interview Questions
- Understand why
std::stringis better: It automatically manages memory, supports simple operators (+, ==), and tracks its own length.
Real-World Example
Comparing the difficulty of concatenation.
example
cpp
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main() {
// C-style way (dangerous and verbose)
char c1[20] = "Hello ";
char c2[] = "World";
strcat(c1, c2);
// C++ way (safe and clean)
string s1 = "Hello ";
string s2 = "World";
string s3 = s1 + s2;
cout << s3 << endl;
return 0;
}