C-Style Strings vs.
std::string
Master the two fundamental approaches to handling text in C++: raw character arrays and the modern string class.
What Is a String?
In programming, a string is a sequence of characters used to represent text: names, messages, file paths, and more. In C++, there are two fundamentally different ways to store strings.
C-Style Strings in Memory
A C-style string is simply a contiguous block of characters in memory, terminated by a null character ('\0'). The null terminator tells functions where the string ends.
std::string Under the Hood
std::string is a class that internally manages a dynamic character array. It tracks both the length and the capacity of the buffer and resizes automatically when needed.
Declaring C-Style vs. std::string
The Core Rule
Key Distinction: Operations
| Operation | C-Style | std::string |
|---|---|---|
| Get length | strlen(s) | s.size() |
| Copy | strcpy(dst, src) | dst = src |
| Concatenate | strcat(dst, src) | s1 + s2 |
| Compare | strcmp(a, b) == 0 | a == b |
| Find substring | strstr(s, sub) | s.find(sub) |
| Safety | Buffer overflow risk | Bounds-managed |
How to Choose
Example: Basic Operations
Example: The Danger of Overflow
Example: Converting Between Types
Example: The Comparison Trap
Common Mistakes
Summary Comparison
| Feature | char[] / char* | std::string |
|---|---|---|
| Memory | Manual | Automatic |
| Resizable | No | Yes |
| Knows its length | No (must scan) | Yes (.size()) |
| Comparison | strcmp() | == |
| Concatenation | strcat() | + |
| Safety | Overflow risk | Bounds-checked |
| Performance | Slight edge | Near-identical |
| Use when | C interop, embedded | Everything else |
Key Takeaways
Question 1 of 5
What character terminates a C-style string in memory?
Question 2 of 5
What does the == operator compare when used on two C-style string variables (e.g., char a[] and char b[])?
Question 3 of 5
How do you convert a std::string to a const char* for passing to a C library function?
Question 4 of 5
You declare char buf[5] = "Hello"; in your program. What happens?
Question 5 of 5
Which of the following is a key advantage of std::string over C-style strings?