跳到主要内容

std::string 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,元素是字节(char 类型的对象),如果使用多字节编码(如 UTF-8),则与字符不同。

示例

Main.cpp
#include <cassert>
#include <iterator>
#include <string>

int main()
{
std::string s("Exemplar");
assert(8 == s.size());
assert(s.size() == s.length());
assert(s.size() == static_cast<std::string::size_type>(
std::distance(s.begin(), s.end())));

std::u32string a(U"ハロー・ワールド"); // 8 code points
assert(8 == a.size()); // 8 code units in UTF-32

std::u16string b(u"ハロー・ワールド"); // 8 code points
assert(8 == b.size()); // 8 code units in UTF-16

std::string c("ハロー・ワールド"); // 8 code points
assert(24 == c.size()); // 24 code units in UTF-8

#if __cplusplus >= 202002
std::u8string d(u8"ハロー・ワールド"); // 8 code points
assert(24 == d.size()); // 24 code units in UTF-8
#endif
}
本文档源自 此 CppReference 页面。它可能为了改进或编辑者偏好而进行了修改。单击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。

std::string 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,元素是字节(char 类型的对象),如果使用多字节编码(如 UTF-8),则与字符不同。

示例

Main.cpp
#include <cassert>
#include <iterator>
#include <string>

int main()
{
std::string s("Exemplar");
assert(8 == s.size());
assert(s.size() == s.length());
assert(s.size() == static_cast<std::string::size_type>(
std::distance(s.begin(), s.end())));

std::u32string a(U"ハロー・ワールド"); // 8 code points
assert(8 == a.size()); // 8 code units in UTF-32

std::u16string b(u"ハロー・ワールド"); // 8 code points
assert(8 == b.size()); // 8 code units in UTF-16

std::string c("ハロー・ワールド"); // 8 code points
assert(24 == c.size()); // 24 code units in UTF-8

#if __cplusplus >= 202002
std::u8string d(u8"ハロー・ワールド"); // 8 code points
assert(24 == d.size()); // 24 code units in UTF-8
#endif
}
本文档源自 此 CppReference 页面。它可能为了改进或编辑者偏好而进行了修改。单击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。