std::basic_string<CharT,Traits,Allocator>::size, std::basic_string<CharT,Traits,Allocator>::length
来自cppreference.com
                    
                                        
                    < cpp | string | basic string
                    
                                                            
                    |   size_type size() const;  | 
(C++11 前) | |
|   size_type size() const noexcept;  | 
 (C++11 起)  (C++20 前)  | 
|
|   constexpr size_type size() const noexcept;  | 
(C++20 起) | |
|   size_type length() const;  | 
(C++11 前) | |
|   size_type length() const noexcept;  | 
 (C++11 起)  (C++20 前)  | 
|
|   constexpr size_type length() const noexcept;  | 
(C++20 起) | |
返回 string 中的 CharT 元素数,即 std::distance(begin(), end()) 。
参数
(无)
返回值
string 中的 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 的编码单元 }
参阅
|   检查字符串是否为空  (公开成员函数)  | |
|   返回字符数的最大值  (公开成员函数)  |