std::string_view
零拷贝字符串视图、substr 高效、与 string/char* 互操作
std::string_view
string_view(C++17)是对字符串的只读视图——不拷贝、不拥有、可引用 string、char*、字面量。
学完本章你将: 掌握零拷贝字符串视图、substr 高效、与各种字符串互操作。
为什么需要 string_view
cpp
#include <string_view>
#include <iostream>
// ❌ const string& —— 只能接受 std::string
void print(const std::string& s) { std::cout << s; }
// ✅ string_view —— 接受 string、char*、字面量
void print(std::string_view sv) {
std::cout << sv;
}
int main() {
std::string s = "Hello";
const char* c = "World";
print(s); // ✅ 从 std::string
print(c); // ✅ 从 C 字符串
print("!!!"); // ✅ 从字面量
print(s.substr(0, 3)); // ✅ 从子串——不分配内存!
}
substr 零拷贝
cpp
std::string s = "Hello World";
std::string sub1 = s.substr(0, 5); // 拷贝 5 个字符
std::string_view sv = s;
std::string_view sub2 = sv.substr(0, 5); // 零拷贝!只调整指针
// sub2 指向 s 的内部——小心悬空
// s.clear(); // sub2 变成悬空引用
常用操作
cpp
std::string_view sv = "Hello World";
sv.size(); // 11
sv.empty(); // false
sv[0]; // 'H'
sv.front(); sv.back();
sv.remove_prefix(6); // sv 变为 "World"
sv.remove_suffix(1); // sv 变为 "Worl"
sv.find("World"); // 查找子串位置
sv.starts_with("He");// C++20
sv.ends_with("ld"); // C++20