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

出自cppreference.com
< cpp‎ | string‎ | basic string
 
 
 
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()); // 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> 的公開成員函數) [編輯]