std::basic_string<CharT,Traits,Allocator>:: size, std::basic_string<CharT,Traits,Allocator>:: length
From cppreference.net
<
cpp
|
string
|
basic string
C++
Strings library
| Classes | ||||
|
(C++17)
|
||||
std::basic_string
|
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
size_type size
(
)
const
;
|
(1) |
(自 C++11 起为 noexcept)
(自 C++20 起为 constexpr) |
|
size_type length
(
)
const
;
|
(2) |
(自 C++11 起为 noexcept)
(自 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 个码点 assert(8 == a.size()); // UTF-32 中的 8 个码元 std::u16string b(u"ハロー・ワールド"); // 8 个码点 assert(8 == b.size()); // UTF-16 中的 8 个码元 std::string c("ハロー・ワールド"); // 8 个码点 assert(24 == c.size()); // UTF-8 中的 24 个码元 #if __cpp_lib_char8_t >= 201907L std::u8string d(u8"ハロー・ワールド"); // 8 个码点 assert(24 == d.size()); // UTF-8 中的 24 个码元 #endif }
参见
|
检查字符串是否为空
(公开成员函数) |
|
|
返回最大字符数
(公开成员函数) |
|
|
返回字符数量
(
std::basic_string_view<CharT,Traits>
的公开成员函数)
|