std::string_view size() 方法
- 自 C++17 起
// Const version only
constexpr size_type size() const noexcept;
// Const version only
constexpr size_type length() const noexcept;
返回容器中元素的数量(CharT
s),即 std::distance(begin(), end())
。
参数
(无)
返回值
容器中元素的数量(CharT
s)。
复杂度
常数 - O(1)。
备注
对于 std::string_view
,元素是字节(char
类型的对象),如果使用多字节编码(如 UTF-8),则与字符不同。
示例
Main.cpp
#include <string_view>
#include <iostream>
void check_string(std::string_view ref)
{
// Print a string surrounded by single quotes, its length
// and whether it is considered empty.
std::cout << std::boolalpha
<< "'" << ref << "' has " << ref.size()
<< " character(s); emptiness: " << ref.empty() << '\n';
}
int main(int argc, char **argv)
{
// An empty string
check_string("");
// Almost always not empty: argv[0]
if (argc > 0)
check_string(argv[0]);
}
可能输出
'' has 0 character(s); emptiness: true
'./a.out' has 7 character(s); emptiness: false