Handling text strings is fundamental to all software systems. C++ provides two main string paradigms: legacy C-style strings (null-terminated character arrays char*) and the powerful, dynamic std::string class, alongside the modern zero-copy std::string_view (C++17).
std::string vs std::string_view| Feature | C-String (char*) |
std::string |
std::string_view (C++17) |
|---|---|---|---|
| Memory Location | Stack or Read-Only Data | Stack (SSO) or Heap | Stack (View only: Pointer + Length) |
| Ownership | Manual pointer management | Owns its heap buffer (RAII) | Non-owning observer |
| Size Lookup | $O(N)$ via strlen() |
$O(1)$ via .size() |
$O(1)$ via .size() |
| Substrings | Requires manual memory allocation | Creates expensive heap copy | $O(1)$ Zero-copy window slice! |
std::string_view#include <iostream>
#include <string>
#include <string_view>
// Efficient function accepting literals, std::string, and char arrays without ANY copy
void printPreview(std::string_view text) {
// Slices first 10 characters in O(1) time without allocating heap RAM!
std::string_view prefix = text.substr(0, 10);
std::cout << "Preview: " << prefix << "\n";
}
int main() {
std::string fullArticle = "Modern C++ Programming Tutorials on Veewom";
printPreview(fullArticle); // Works with std::string
printPreview("Hello World string literal"); // Works with string literals!
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
Reading multi-word strings with std::getline.
Understanding char* pointers and string literals.
Features of C++17 including string_view.