命名空间
变体
操作

std::basic_string<CharT,Traits,Allocator>::size, std::basic_string<CharT,Traits,Allocator>::length

来自 cppreference.cn
< cpp‎ | string‎ | basic string
 
 
 
std::basic_string
 
size_type size() const;
(1) (noexcept since C++11)
(constexpr since C++20)
size_type length() const;
(2) (noexcept since C++11)
(constexpr since C++20)

返回字符串中 CharT 元素的数量,即 std::distance(begin(), end())

目录

[edit] 参数

(无)

[edit] 返回值

字符串中 CharT 元素的数量。

[edit] 复杂度

未指定

(C++11 前)

常数

(C++11 起)

[edit] 注意

对于 std::string,元素是字节(char 类型的对象),如果使用多字节编码(如 UTF-8),则字节与字符不相同。

[edit] 示例

#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
}

[edit] 参见

检查字符串是否为空
(公共成员函数) [编辑]
返回最大字符数
(公共成员函数) [编辑]
返回字符数
(std::basic_string_view<CharT,Traits> 的公共成员函数) [编辑]