C++•Strings
C++ std::string and std::string_view (C++17)
Learn std::string operations (substring, concatenation, find) and modern C++17 std::string_view for zero-copy string slicing.
Syntax
#include <string>
#include <string_view>
std::string str = "hello";
std::string_view view = str;
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| std::string | Class | Dynamic heap-allocated mutable string container. |
| std::string_view | C++17 View | Non-owning read-only view of a contiguous character buffer. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C++ locally:
#include <iostream>
#include <string>
#include <string_view>
// Pass by string_view for zero-copy function parameters
void inspectToken(std::string_view token) {
std::cout << "Token: [" << token << "] (Length: " << token.length() << ")\n";
}
int main() {
std::string fullPath = "/usr/local/bin/compilra";
// Find and substring
size_t lastSlash = fullPath.find_last_of('/');
if (lastSlash != std::string::npos) {
std::string filename = fullPath.substr(lastSlash + 1);
std::cout << "Extracted File: " << filename << "\n";
}
// Zero-copy string_view call
inspectToken("AUTH_TOKEN_BEARER_8841");
return 0;
}Expected Output:
Extracted File: compilra Token: [AUTH_TOKEN_BEARER_8841] (Length: 23)
How It Works: Step-by-Step
- Lines 6-8: Accepts std::string_view for zero allocation parameter passing.
- Lines 14-17: Finds last slash position and slices file name using substr().
Key Concepts
- std::string manages dynamic heap memory with Small String Optimization (SSO).
- std::string_view (C++17) provides zero-copy read-only views into string literals or std::string.
- Check find results against std::string::npos to verify matches.
Common Mistake: Returning a string_view pointing to a temporary local std::string
A string_view does not own memory; returning it for a destroyed local string creates a dangling pointer.
❌ Incorrect
std::string_view getName() {
std::string local = "data";
return local; // Dangling reference!
}✅ Correct
std::string getName() {
return "data"; // Safe by value
}Related C++ Tutorials & Compiler
C++ std::vector (Dynamic Arrays): Methods and Memory
Master std::vector for dynamic contiguous arrays with push_back, emplace_back, and indexing.
C++ Input and Output: std::cin, std::cout, and getline
Learn how to read from stdin with std::cin and std::getline, and format output stream data.
C++ Variables and Primitive Data Types with Examples
Learn how to declare typed variables in C++ including int, double, char, bool, and auto.
C++ Online Compiler
Open in Compilra IDE
Run and test C++ on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.