std::basic_string<CharT,Traits,Allocator>::size, std::basic_string<CharT,Traits,Allocator>::length
来自 cppreference.cn
< cpp | string | basic_string
size_type size() const; |
(1) | (C++11 起无异常抛出) (C++20 起为 constexpr) |
size_type length() const; |
(2) | (C++11 起无异常抛出) (C++20 起为 constexpr) |
返回字符串中 `CharT` 元素的数量,即 std::distance(begin(), end())。
目录 |
[编辑] 参数
(无)
[编辑] 返回值
字符串中 `CharT` 元素的数量。
[编辑] 复杂度
未指定 |
(C++11 前) |
常数时间 |
(C++11 起) |
[编辑] 注解
对于 std::string,元素是字节(char 类型的对象),如果使用多字节编码(如 UTF-8),则与字符不同。
[编辑] 示例
运行此代码
#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 __cpp_lib_char8_t >= 201907L std::u8string d(u8"ハロー・ワールド"); // 8 code points assert(24 == d.size()); // 24 code units in UTF-8 #endif }
[编辑] 参阅
检查字符串是否为空 (public 成员函数) | |
返回字符的最大数量 (public 成员函数) | |
返回字符数 (`std::basic_string_view<CharT,Traits>` 的公共成员函数) |