std::basic_string<CharT,Traits,Allocator>::size, std::basic_string<CharT,Traits,Allocator>::length
來自 cppreference.com
< 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>` 的公共成員函式) |