std::basic_string<CharT,Traits,Allocator>::size, std::basic_string<CharT,Traits,Allocator>::length
来自cppreference.com
<tbody>
</tbody>
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()); // 8 个 UTF-32 的编码单元
std::u16string b(u"ハロー・ワールド"); // 8 个码点
assert(8 == b.size()); // 8 个 UTF-16 的编码单元
std::string c(u8"ハロー・ワールド"); // 8 个码点
assert(24 == c.size()); // 24 个 UTF-8 的编码单元
#if __cpp_lib_char8_t >= 201907L
std::u8string d(u8"ハロー・ワールド"); // 8 个码点
assert(24 == d.size()); // 24 个 UTF-8 的编码单元
#endif
}
参阅
| 检查字符串是否为空 (公开成员函数) | |
| 返回字符数的最大值 (公开成员函数) | |
| 返回字符数 ( std::basic_string_view<CharT,Traits> 的公开成员函数)
|