Table of Contents

<string_view>

<string_view> provides std::string_view<CharT>, a non-owning view over a character sequence (C++17). It holds a pointer and length, allowing you to pass string data without copying or null-terminating.

Use it as a function parameter when you don't need ownership; it accepts both std::string and string literals with zero overhead.

Example

This example passes both owned strings and string literals to the same function via string_view, and extracts substrings.

// compile: g++ -std=c++17 -o stringviewexample stringviewexample.cpp
// run: ./stringviewexample
// description: string_view as a parameter type
 
#include <string_view>
#include <string>
#include <iostream>
 
void print_string(std::string_view sv) {
    std::cout << "length: " << sv.length() << ", data: " << sv << "\n";
}
 
int main() {
    std::string s = "hello";
    print_string(s);
 
    print_string("world");
 
    std::string_view part = s.substr(0, 3);
    std::cout << "substr: " << part << "\n";
 
    return 0;
}