此头文件是字符串库的一部分。本篇介绍string_view的基本用法。
函数 | |
以字典序比较两个字符串视图 (函数模板) | |
(C++17) | 进行字符串视图的流输出 (函数模板) |
交换两个对象的值 (函数模板) | |
范围访问 | |
(C++11)(C++14) | 返回指向容器或数组起始的迭代器 (函数模板) |
(C++11)(C++14) | 返回指向容器或数组结尾的迭代器 (函数模板) |
(C++14) | 返回指向一个容器或数组的逆向迭代器 (函数模板) |
(C++14) | 返回容器或数组的逆向尾迭代器 (函数模板) |
(C++17)(C++20) | 返回容器或数组的大小 (函数模板) |
(C++17) | 检查容器是否为空 (函数模板) |
(C++17) | 获得指向底层数组的指针 (函数模板) |
示例代码:
#include <iomanip>
#include <iostream>
#include <string_view>
#include <cstring>
//https://zh.cppreference.com/w/cpp/header/string_view
#pragma warning(disable:4996)
//C4996 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
//C++17标准
int main()
{
//operator<< example (C++17)进行字符串视图的流输出
constexpr std::string_view s{ "abc" };
constexpr int width{ 5 };
// fill/left/right 属性保留不变直至被修改
std::cout << std::setfill('-');
std::cout << std::left;
std::cout << '[' << std::setw(width) << s << "]\n";
std::cout << '[' << std::setw(width) << s << "]\n";
std::cout << std::right;
std::cout << '[' << std::setw(width) << s << "]\n";
// 每次调用后重置宽度
std::cout << '[' << s << "]\n";
//swap example
std::string_view s1{ "first" };
std::string_view s2{ "were" };
std::cout << "s1===========" << s1 << "\n";
std::cout << "s2===========" << s2 << "\n";
s2.swap(s1);
std::cout << "s1===========" << s1 << "\n";
std::cout << "s2===========" << s2 << "\n";
//operator== example
std::cout << "(s1==s2)=============" << (s1 == s2) << "\n";
const char* source = "123456789";
char dest[20];
strcpy_s(dest, 10, source);//numberOfElements等于字符串大小
std::cout << dest << "*\n";
//data example
std::string_view s3{"hello world"};
char a3[32] = {'\0'};
const char* src = s3.data();
std::cout << "src==========" << src << "\n";
std::strcpy(a3, s3.data());
std::cout << "s3===========" << s3 << "\n";
std::cout << "a3===========" << a3 << "\n";
//empty example
std::cout << "s3.empty=====" << s3.empty() << "\n";
//size example
std::cout << "s3.size======" << s3.size() << "\n";
//begin example
//std::string_view::iterator it = s3.begin();
auto begin = s3.begin();
std::cout << "begin========" << *begin << "\n";
//cbegin example
auto cbegin = s3.cbegin();
std::cout << "cbegin=======" << *cbegin << "\n";
//end example
auto end = s3.end();
end--;
std::cout << "end==========" << *end << "\n";
//cend example
auto cend = s3.cend();
cend--;
std::cout << "cend=========" << *cend << "\n";
//begin,cbegin,end,cend是一样的都不能修改值
//rbegin example
auto rbegin = s3.rbegin();
std::cout << "rbegin========" << *rbegin << "\n";
//crbegin example
auto crbegin = s3.crbegin();
std::cout << "crbegin=======" << *crbegin << "\n";
//rend example
auto rend = s3.rend();
rend--;
std::cout << "rend==========" << *rend << "\n";
//crend example
auto crend = s3.crend();
crend--;
std::cout << "crend=========" << *crend << "\n";
}
运行结果:
参考: