跳到主要内容

std::string_view size() 方法

// Const version only
constexpr size_type size() const noexcept;

// Const version only
constexpr size_type length() const noexcept;

返回容器中元素的数量(CharTs),即 std::distance(begin(), end())

参数

(无)

返回值

容器中元素的数量(CharTs)。

复杂度

常数 - 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
本文来源于 此 CppReference 页面。它可能为了改进或编辑者偏好而进行了修改。点击“编辑此页面”查看本文档所做的所有更改。
悬停查看原始许可证。

std::string_view size() 方法

// Const version only
constexpr size_type size() const noexcept;

// Const version only
constexpr size_type length() const noexcept;

返回容器中元素的数量(CharTs),即 std::distance(begin(), end())

参数

(无)

返回值

容器中元素的数量(CharTs)。

复杂度

常数 - 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
本文来源于 此 CppReference 页面。它可能为了改进或编辑者偏好而进行了修改。点击“编辑此页面”查看本文档所做的所有更改。
悬停查看原始许可证。